如何在 PHP 中將陣列轉換為 SimpleXML?


我們可以使用 array_walk_recursive() 函式解決以上問題。array_walk_recursive()   是一個內建的 PHP 函式。該函式將陣列轉換為 XML 文件,其中陣列的鍵被轉換為值,而陣列的值被轉換為 XML 的元素。

我們用一個簡單的示例來說明一下。

示例

<?php
   $array = array (
   'name' => 'alex',
   'empdept' => 'account',
   'address' => array (
      'city' => 'michigan'
      ),
   );
   //This function create a xml object with element root.
   $xml = new SimpleXMLElement('');
   array_walk_recursive($array, array ($xml,'addChild'));
   print $xml->asXML();
?>

輸出

<?xml version="1.0"?>
<root>
<name> alex </name>
<empdept> account </empdept>
<city> michigan </city >
</root>

注意

如果出現錯誤訊息,如 PHP 致命錯誤:未找到類 'SimpleXMLElement',只需安裝 php-xml、php-simplexml 包即可。

更新時間: 2020 年 6 月 29 日

3K+ 瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.