PHP中數(shù)組轉(zhuǎn)換為SimpleXML教程
SimpleXML擴展函數(shù)提供了將XML轉(zhuǎn)換為對象的工具集。這些對象處理普通的屬性選擇器和數(shù)組迭代器。
示例1:
<?php // 將php數(shù)組轉(zhuǎn)換為xml文檔的代碼 //定義一個將數(shù)組轉(zhuǎn)換成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)) { // 調(diào)用嵌套數(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' ), ); // 調(diào)用arrayToxml函數(shù)并打印結(jié)果 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ù)組轉(zhuǎn)換為xml文檔,其中數(shù)組的鍵轉(zhuǎn)換為值,數(shù)組的值轉(zhuǎn)換為xml的元素。
示例2:
<?php // 將php數(shù)組轉(zhuǎn)換為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軟件包。
相關(guān)文章
PHP隨機數(shù)函數(shù)rand()與mt_rand()的講解
今天小編就為大家分享一篇關(guān)于PHP隨機數(shù)函數(shù)rand()與mt_rand()的講解,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-03-03mysql_fetch_assoc和mysql_fetch_row的功能加起來就是mysql_fetch_array
mysql_fetch_assoc和mysql_fetch_row的功能加起來就是mysql_fetch_array...2007-01-01php實現(xiàn)的Curl封裝類Curl.class.php用法實例分析
這篇文章主要介紹了php實現(xiàn)的Curl封裝類Curl.class.php用法,以完整實例形式較為詳細的分析了Curl封裝類的定義及相關(guān)使用技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-09-09require(),include(),require_once()和include_once()的異同
require(),include(),require_once()和include_once()的異同...2007-01-01