如何在PHP中将数组转换为SimpleXML对象?
一个简短的:
<?php $test_array = array ( 'bla' => 'blub', 'foo' => 'bar', 'another_array' => array ( 'stack' => 'overflow', ), ); $xml = new SimpleXMLElement('<root/>'); array_walk_recursive($test_array, array ($xml, 'addChild')); print $xml->asXML();
结果是
<?xml version="1.0"?> <root> <blub>bla</blub> <bar>foo</bar> <overflow>stack</overflow> </root>
键和值被交换- 您可以array_flip()在array_walk之前用来解决。array_walk_recursive需要PHP5。您可以改用PHP 5 array_walk,但'stack' => 'overflow'那时您将不会进入xml。
array_flip()
array_walk_recursive
array_walk
'stack' => 'overflow'