通过XML命名空间PHP循环
问题描述:
我有这样的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 & Suits</dispengnm>
<dispnm>Gaun & 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
(
)
答
您需要设置getNamespaces
到true
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;
}
感谢人,它的作用就像一个魅力 –