2017-04-10 105 views
1

我有這樣的XML捲曲響應:通過XML命名空間PHP循環

<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> 

我嘗試使用此代碼來獲取<ns2:category>裏面的數據:

$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); 
} 

但我得到的是:

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

回答

1

您需要設置getNamespacestrue befor e循環數據,並且在循環內需要調用子函數,以便獲取數據並將其包含在對象變量中

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

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

感謝人,它的作用就像一個魅力 –