首頁  >  文章  >  後端開發  >  php如何將xml轉換為array數組

php如何將xml轉換為array數組

青灯夜游
青灯夜游原創
2021-02-24 11:00:223335瀏覽

方法:先用simplexml_load_string()將XML字串轉換為SimpleXMLElement物件;然後用json_encode()將該物件轉換為JSON資料;最後用json_decode()將JSON資料轉換為陣列即可。

php如何將xml轉換為array數組

本教學操作環境:windows7系統、PHP7.1版,DELL G3電腦

php將xml轉換為array數

1、函數:

/*
@desc:xml转数组
@param data xml字符串
@return arr 解析出的数组
*/
function xmltoarray($data){
$obj = simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA);
$json = json_encode($obj);
$arr = json_decode($json, true);      
return $arr;
}

simplexml_load_string() 函數轉換形式良好的XML 字串為SimpleXMLElement 物件。

json_encode() 用於對變數進行 JSON 編碼,該函數如果執行成功返回 JSON 數據,否則傳回 FALSE 。

json_decode() 函數用於對 JSON 格式的字串進行解碼,並轉換為 PHP 變數(物件或陣列)。

json_decode ($json_string [,$assoc = false [, $depth = 512 [, $options = 0 ]]])

參數

  • json_string: 待解碼的JSON 字串,必須是UTF-8 編碼資料

  • assoc:當此參數為TRUE 時,將傳回數組,FALSE 時傳回物件。

  • depth: 整數型別的參數,它指定遞歸深度

  • options: 二進位掩碼,目前只支援 JSON_BIGINT_AS_STRING 。

2、測試:

a.程式碼:

<?php
$string = <<<XML
<?xml version=&#39;1.0&#39;?> 
<document>
<title>Forty What?</title>
<from>Joe</from>
<to>Jane</to>
<body>
I know that&#39;s the answer -- but what&#39;s the question?
</body>
</document>
XML;
$arr = xmltoarray($string);
var_dump($arr);

b. 輸出:

array(4) {
["title"]=>
string(11) "Forty What?"
["from"]=>
string(3) "Joe"
["to"]=>
string(4) "Jane"
["body"]=>
string(57) "
I know that&#39;s the answer -- but what&#39;s the question?
"
}

更多程式相關知識,請造訪:程式設計影片! !

以上是php如何將xml轉換為array數組的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn