3v4l.org

run code in 300+ PHP versions simultaneously
<?php function arrayToXml($array, \SimpleXMLElement $xml) { foreach ($array as $key => $value) { if (is_array($value)) { if (!is_numeric($key)) { $subNode = $xml->addChild($key); } else { $subNode = $xml->addChild('item' . $key); } arrayToXml($value, $subNode); } else { $xml->addChild($key, htmlspecialchars($value)); } } } $array = [ 'key' => 'value', 'arrKey' => [ 'subkey1' => 1, 'subkey2' => 2, ], 0 => 'numeric zero', 1 => 'another', 2 => [ 'adin', 'two', 'three' ], ]; $xml = new \SimpleXMLElement('<response/>'); arrayToXml($array, $xml); echo $xml->asXML(); echo PHP_EOL; $xml = new SimpleXMLElement('<response/>'); array_walk_recursive($array, array ($xml, 'addChild')); print $xml->asXML();
Output for 5.4.0 - 5.4.45, 5.5.0 - 5.5.38, 5.6.0 - 5.6.28, 7.0.0 - 7.0.20, 7.1.0 - 7.1.10, 7.2.0 - 7.2.33, 7.3.16 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.28, 8.2.0 - 8.2.18, 8.3.0 - 8.3.6
<?xml version="1.0"?> <response><key>value</key><arrKey><subkey1>1</subkey1><subkey2>2</subkey2></arrKey><0>numeric zero</0><1>another</1><item2><0>adin</0><1>two</1><2>three</2></item2></response> <?xml version="1.0"?> <response><value>key</value><1>subkey1</1><2>subkey2</2><numeric zero>0</numeric zero><another>1</another><adin>0</adin><two>1</two><three>2</three></response>

preferences:
198.03 ms | 405 KiB | 272 Q