Reputation: 13
I use the code below to get xml data from some API:
<?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);
?>
I get xml data successfully something like
<?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>
but I can't parse and echo only cities using
$parser = simplexml_load_string($response);
foreach($parser->warenhouse as $item) {
echo $item->city;
}
What's wrong?
Upvotes: 1
Views: 957
Reputation: 68476
Your XML is a bit malformed , remove that </xml>
from the end.
You need to loop like this
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
Upvotes: 1