php如何将数组转换为SimpleXML
|
如何在PHP中将数组转换为SimpleXML对象? 最简单的方法: $test_array = array ( 'bla' => 'blub', 'foo' => 'bar', 'another_array' => array ( 'stack' => 'overflow', ), ); $xml = new SimpleXMLElement(' array_walk_recursive($test_array,array ($xml,'addChild')); print $xml->asXML(); 结果是 键和值是交换的 - 您可以使用array_flip()在array_walk之前修复它。 再看一个实例: 这是php 5.2代码,它将任何深度的数组转换为xml文档: 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将如下: PHP代码段 // function defination to convert array to xml function array_to_xml( $data,&$xml_data ) { foreach( $data as $key => $value ) { if( is_numeric($key) ){ $key = 'item'.$key; //dealing with <0/>.. } 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(''); // 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'); ?> (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
