I have the following XML:
<ns1:getBannerLinksResponse xmlns:ns1="http://endpoint.website.com/">
<ns1:return>
<ns1:campaignID>0</ns1:campaignID>
<ns1:categoryID>200230455</ns1:categoryID>
<ns1:categoryName>Promotion</ns1:categoryName>
<ns1:linkID>10001599</ns1:linkID>
<ns1:linkName>KFL-20% off No Min</ns1:linkName>
<ns1:mid>3071</ns1:mid>
<ns1:nid>1</ns1:nid>
<ns1:clickURL>
http://someurl
</ns1:clickURL>
<ns1:endDate>Oct 15, 2012</ns1:endDate>
<ns1:height>250</ns1:height>
<ns1:iconURL>
http://someurl
</ns1:iconURL>
<ns1:imgURL>
http://someurl
</ns1:imgURL>
<ns1:landURL>
http://someurl
</ns1:landURL>
<ns1:serverType>22</ns1:serverType>
<ns1:showURL>
http://someurl
</ns1:showURL>
<ns1:size>13</ns1:size>
<ns1:startDate>Oct 14, 2012</ns1:startDate>
<ns1:width>300</ns1:width>
</ns1:return>
</ns1:getBannerLinksResponse>
I tried the following with no luck:
$data = new SimpleXMLElement($xml);
$data->registerXPathNamespace('ns1','http://endpoint.website.com/');
foreach($data->xpath('//ns1:return') as $banner)
{
$banner->registerXPathNamespace('ns1','http://endpoint.website.com/');
var_dump($banner);
}
You need to use the
->children()
method. If you avoid XPath and just use the SimpleXML operators, your code will end up much simpler.Namespaced elements are also one of many things not visible when using standard PHP debug functions to debug the rather magical SimpleXML objects. (The below uses [my
simplexml_dump()
function instead.)Note that the 'ns1' namespace remains selected until another
->children()
call:If
<return>
can occur multiple times, this obviously becomes:All you need is
Output