Looping through XML with namespace PHP

时间:2017-04-10 02:30:21

标签: php xml curl

I have a xml curl response like this:

<ns2:categorys xmlns:ns2="http://skt.tmall.business.openapi.spring.service.client.domain">
    <ns2:category>
        <depth>1</depth>
        <dispengnm>Women Clothing</dispengnm>
        <dispnm>Pakaian Wanita</dispnm>
        <dispno>1</dispno>
        <parentdispno>0</parentdispno>
    </ns2:category>
    <ns2:category>
        <depth>2</depth>
        <dispengnm>Dresses &amp; Suits</dispengnm>
        <dispnm>Gaun &amp; Terusan</dispnm>
        <dispno>2</dispno>
        <parentdispno>1</parentdispno>
    </ns2:category>
</ns2:categorys>

i tried to get the data inside the <ns2:category> using this code:

$return = curl_exec($ch);

$return= simplexml_load_string($return);
$categories = $return->children('ns2', true);
echo "<pre>";
var_dump(count($categories)); 
foreach ($categories as $category) {
  print_r($category->depth);
}

but all i got is :

int(2)
SimpleXMLElement Object
(
)
SimpleXMLElement Object
(
)

1 个答案:

答案 0 :(得分:1)

You need to set getNamespaces to true before looping the data, and inside the loop you need to call the children function so it will get the data and wrapped it inside an object variable

$return = simplexml_load_string($return);
$ns = $return->getNamespaces(true);

foreach ($return->children($ns['ns2'])->category as $key) {
  $data = $key->children();
  echo  $data->depth;
}