3v4l.org

run code in 500+ PHP versions simultaneously
<?php function array_to_xml( $data, &$xml_data ) { foreach( $data as $key => $value ) { foreach($value as $innerkey => $innervalue) { $v = $innervalue['@value']; $t = ""; if(isset($innervalue['@attributes']['typ'])) { $t = $innervalue['@attributes']['typ']; } $kontakt = $xml_data->addChild('kontakt', $v); $kontakt->addAttribute('typ', $t); } } } $data = array("kontakt"=>[ 1=>[ '@value' => 'abc@abc.pl', '@attributes' => ['typ' => 'email'], ], 2=>[ '@value' => '3123453141', '@attributes' => ['typ' => 'telefon'], ], ] ); $xml_data = new SimpleXMLElement('<test></test>') ; array_to_xml($data,$xml_data); echo $xml_data->asXML();
Output for 7.0.33, 8.1.23 - 8.1.34, 8.2.10 - 8.2.30, 8.3.0 - 8.3.30, 8.4.1 - 8.4.21, 8.5.0 - 8.5.7
<?xml version="1.0"?> <test><kontakt typ="email">abc@abc.pl</kontakt><kontakt typ="telefon">3123453141</kontakt></test>

preferences:
70.76 ms | 873 KiB | 4 Q