无法从curl响应中解析xml

时间:2014-04-08 17:12:32

标签: php xml curl

我使用下面的代码从某些API获取xml数据:

<?php
$ch = curl_init();
$xml = '<?xml version="1.0" encoding="utf-8"><file><auth>myapikey</auth><warenhouse/></file>';
curl_setopt($ch, CURLOPT_URL, 'http://somesite.com/xml.php');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Content-Type: text/xml"));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($ch);
curl_close($ch);
?>

我成功地获得了像

这样的xml数据
<?xml version="1.0" encoding="UTF-8"?>
<response>
<responseCode>200</responseCode>
<result>
<whs>
<warenhouse>
<city>New York City</city>
<address>Some Address</address>
<number>1</number>
<phone>1111111</phone>
</warenhouse>
<warenhouse>
...
</warenhouse>
</whs>
</result>
</response>
</xml>

但是我无法使用

解析和回显城市
$parser = simplexml_load_string($response);
foreach($parser->warenhouse as $item) {
 echo $item->city;
}

怎么了?

1 个答案:

答案 0 :(得分:1)

您的XML格式有点格式错误,请从最后删除</xml>

你需要像这样循环

foreach ($xml->result->whs->warenhouse as $child)
{
        echo $child->city;

}

代码..

<?php
$xml= <<<XML
<?xml version="1.0" encoding="UTF-8" ?>
<response>
<responseCode>200</responseCode>
<result>
<whs>
<warenhouse>
<city>New York City</city>
<address>Some Address</address>
<number>1</number>
<phone>1111111</phone>
</warenhouse>
<warenhouse>
</warenhouse>
</whs>
</result>
</response>
XML;
$xml = simplexml_load_string($xml);
foreach ($xml->result->whs->warenhouse as $child)
{
        echo $child->city;

}

<强> OUTPUT:

New York City

Demo