如何将数组转换为SimpleXML如何在PHP中将数组转换为SimpleXML对象?
3 回答

跃然一笑
TA贡献1826条经验 获得超6个赞
<?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_recursive
array_walk
'stack' => 'overflow'

紫衣仙女
TA贡献1839条经验 获得超15个赞
Array( ['total_stud']=> 500 [0] => Array ( [student] => Array ( [id] => 1 [name] => abc [address] => Array ( [city]=>Pune [zip]=>411006 ) ) ) [1] => Array ( [student] => Array ( [id] => 2 [name] => xyz [address] => Array ( [city]=>Mumbai [zip]=>400906 ) ) ))
<?xml version="1.0"?><student_info> <total_stud>500</total_stud> <student> <id>1</id> <name>abc</name> <address> <city>Pune</city> <zip>411006</zip> </address> </student> <student> <id>1</id> <name>abc</name> <address> <city>Mumbai</city> <zip>400906</zip> </address> </student></student_info>
<?php// function definition to convert array to xmlfunction array_to_xml( $data, &$xml_data ) { foreach( $data as $key => $value ) { if( is_numeric($key) ){ $key = 'item'.$key; //dealing with <0/>..<n/> issues } if( is_array($value) ) { $subnode = $xml_data->addChild($key); array_to_xml($value, $subnode); } else { $xml_data->addChild("$key",htmlspecialchars("$value")); } }}// initializing or creating array$data = array('total_stud' => 500); // creating object of SimpleXMLElement$xml_data = new SimpleXMLElement('<?xml version="1.0"?><data></data>'); // function call to convert array to xml array_to_xml($data,$xml_data); //saving generated xml file; $result = $xml_data->asXML('/file/path/name.xml');?>
SimpleXMLElement::asXML
- 3 回答
- 0 关注
- 521 浏览
相关问题推荐
添加回答
举报
0/150
提交
取消