SimpleXML擴展函數提供了將XML轉換為對象的工具集。這些對象處理普通的屬性選擇器和數組迭代器。
示例1:
?php
// 將php數組轉換為xml文檔的代碼
//定義一個將數組轉換成xml的函數。
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) {
// 如果有嵌套數組
if (is_array($v)) {
// 調用嵌套數組的函數
arrayToXml($v, $k, $_xml->addChild($k));
}
else {
$_xml->addChild($k, $v);
}
}
return $_xml->asXML();
}
// 創建一個用于演示的數組
$my_array = array (
'name' => 'GFG',
'subject' => 'CS',
// 創建嵌套數組。
'contact_info' => array (
'city' => 'Noida',
'state' => 'UP',
'email' => '448199179@qq.com'
),
);
// 調用arrayToxml函數并打印結果
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()函數解決上述問題。此函數將數組轉換為xml文檔,其中數組的鍵轉換為值,數組的值轉換為xml的元素。
示例2:
?php
// 將php數組轉換為xml文檔的代碼
//創建一個數組
$my_array = array (
'a' => 'x',
'b' => 'y',
// creating nested array
'another_array' => array (
'c' => 'z',
),
);
// 這個函數使用root元素創建一個xml對象。
$xml = new SimpleXMLElement('root/>');
// 這個函數重新將數組元素添加到xml文檔中
array_walk_recursive($my_array, array ($xml, 'addChild'));
// 這個函數打印xml文檔。
print $xml->asXML();
?>
輸出:
?xml version =“1.0”?> root>
x> a / x>
y> b / y>
z> c / z> / root>
注:
如果系統生成錯誤類型:
PHP Fatal error: Uncaught Error: Class ‘SimpleXMLElement' not found in /home/6bc5567266b35ae3e76d84307e5bdc78.php:24 ,
那么只需安裝php-xml,php-simplexml軟件包。
您可能感興趣的文章:- PHP簡單實現解析xml為數組的方法
- PHP實現的數組和XML文件相互轉換功能示例
- PHP實現使用DOM將XML數據存入數組的方法示例
- php實現XML和數組的相互轉化功能示例
- php實現xml轉換數組的方法示例
- PHP數組生成XML格式數據的封裝類實例