SimpleXML擴展函數(shù)提供了將XML轉換為對象的工具集。這些對象處理普通的屬性選擇器和數(shù)組迭代器。
示例1:
?php // 將php數(shù)組轉換為xml文檔的代碼 //定義一個將數(shù)組轉換成xml的函數(shù)。 function arrayToXml($array, $rootElement = null, $xml = null) { $_xml = $xml; // 如果沒有$rootElement,則插入$rootElement if ($_xml === null) { $_xml = new SimpleXMLElement($rootElement !== null ? $rootElement : 'root/>'); } // 訪問所有鍵值對 foreach ($array as $k => $v) { // 如果有嵌套數(shù)組 if (is_array($v)) { // 調用嵌套數(shù)組的函數(shù) arrayToXml($v, $k, $_xml->addChild($k)); } else { $_xml->addChild($k, $v); } } return $_xml->asXML(); } // 創(chuàng)建一個用于演示的數(shù)組 $my_array = array ( 'name' => 'GFG', 'subject' => 'CS', // 創(chuàng)建嵌套數(shù)組。 'contact_info' => array ( 'city' => 'Noida', 'state' => 'UP', 'email' => '448199179@qq.com' ), ); // 調用arrayToxml函數(shù)并打印結果 echo arrayToXml($my_array); ?>
輸出:
?xml version="1.0"?> root> name> GFG /name> subject> CS /subject> contact_info > city > Noida /city > state > UP /state > email > 448199179@qq.com /email> contact_info> root>
可以使用array_walk_recursive()函數(shù)解決上述問題。此函數(shù)將數(shù)組轉換為xml文檔,其中數(shù)組的鍵轉換為值,數(shù)組的值轉換為xml的元素。
示例2:
?php // 將php數(shù)組轉換為xml文檔的代碼 //創(chuàng)建一個數(shù)組 $my_array = array ( 'a' => 'x', 'b' => 'y', // creating nested array 'another_array' => array ( 'c' => 'z', ), ); // 這個函數(shù)使用root元素創(chuàng)建一個xml對象。 $xml = new SimpleXMLElement('root/>'); // 這個函數(shù)重新將數(shù)組元素添加到xml文檔中 array_walk_recursive($my_array, array ($xml, 'addChild')); // 這個函數(shù)打印xml文檔。 print $xml->asXML(); ?>
輸出:
?xml version =“1.0”?> root> x> a / x> y> b / y> z> c / z> / root>
注:
如果系統(tǒng)生成錯誤類型:
PHP Fatal error: Uncaught Error: Class ‘SimpleXMLElement' not found in /home/6bc5567266b35ae3e76d84307e5bdc78.php:24 ,
那么只需安裝php-xml,php-simplexml軟件包。