php怎么將xml轉(zhuǎn)為array數(shù)組

這篇文章主要介紹php怎么將xml轉(zhuǎn)為array數(shù)組,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!

合水網(wǎng)站制作公司哪家好,找成都創(chuàng)新互聯(lián)!從網(wǎng)頁設(shè)計(jì)、網(wǎng)站建設(shè)、微信開發(fā)、APP開發(fā)、成都響應(yīng)式網(wǎng)站建設(shè)等網(wǎng)站項(xiàng)目制作,到程序開發(fā),運(yùn)營維護(hù)。成都創(chuàng)新互聯(lián)于2013年成立到現(xiàn)在10年的時(shí)間,我們擁有了豐富的建站經(jīng)驗(yàn)和運(yùn)維經(jīng)驗(yàn),來保證我們的工作的順利進(jìn)行。專注于網(wǎng)站建設(shè)就選成都創(chuàng)新互聯(lián)。

方法:首先用simplexml_load_string()將XML字符串轉(zhuǎn)換為SimpleXMLElement對象;然后用json_encode()將該對象轉(zhuǎn)換為JSON數(shù)據(jù);最后用json_decode()將JSON數(shù)據(jù)轉(zhuǎn)換為數(shù)組即可。

php將xml轉(zhuǎn)換為array數(shù)

1、函數(shù):

/*
@desc:xml轉(zhuǎn)數(shù)組
@param data xml字符串
@return arr 解析出的數(shù)組
*/
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() 函數(shù)轉(zhuǎn)換形式良好的 XML 字符串為 SimpleXMLElement 對象。

json_encode() 用于對變量進(jìn)行 JSON 編碼,該函數(shù)如果執(zhí)行成功返回 JSON 數(shù)據(jù),否則返回 FALSE 。

json_decode() 函數(shù)用于對 JSON 格式的字符串進(jìn)行解碼,并轉(zhuǎn)換為 PHP 變量(對象或數(shù)組)。

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

參數(shù)

  • json_string: 待解碼的 JSON 字符串,必須是 UTF-8 編碼數(shù)據(jù)

  • assoc: 當(dāng)該參數(shù)為 TRUE 時(shí),將返回?cái)?shù)組,F(xiàn)ALSE 時(shí)返回對象。

  • depth: 整數(shù)類型的參數(shù),它指定遞歸深度

  • options: 二進(jìn)制掩碼,目前只支持 JSON_BIGINT_AS_STRING 。

2、測試:

a. 代碼:

<?php
$string = <<<XML
<?xml version='1.0'?> 
<document>
<title>Forty What?</title>
<from>Joe</from>
<to>Jane</to>
<body>
I know that's the answer -- but what'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's the answer -- but what's the question?
"
}

以上是“php怎么將xml轉(zhuǎn)為array數(shù)組”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!

分享題目:php怎么將xml轉(zhuǎn)為array數(shù)組
本文鏈接:http://muchs.cn/article48/ihgoep.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站內(nèi)鏈、網(wǎng)站制作、軟件開發(fā)、品牌網(wǎng)站制作、靜態(tài)網(wǎng)站網(wǎng)站營銷

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

成都做網(wǎng)站