[英]How to parse a xml string to array in PHP?
我正在使用 API 給我一個 XML 響應(帶卷曲)我需要解析響應以獲得特定值
我遵循 php 文檔
<?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;
$xml = simplexml_load_string($string);
print_r($xml);
?>
但在我的情況下,curl 的響應是這樣的,沒有 <<<XML XML; tag 和 simplexml_load_string 給我空的 object
`
<?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 object 編碼為 JSON 將其轉換為關聯數組,然后將其解碼回數組,如下所示:
$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;
$xml = simplexml_load_string($string);
$xml = json_encode($xml);
$xml = json_decode($xml, true);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.