使用PHP名称空间循环XML
我有一个xml curl响应,如下所示:使用PHP名称空间循环XML,php,xml,curl,Php,Xml,Curl,我有一个xml curl响应,如下所示: <ns2:categorys xmlns:ns2="http://skt.tmall.business.openapi.spring.service.client.domain"> <ns2:category> <depth>1</depth> <dispengnm>Women Clothing</dispengnm> <
<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>
在循环数据之前,需要将
getNamespaces
设置为true
,在循环中需要调用children函数,以便它获取数据并将其包装到对象变量中
$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
(
)
$return = simplexml_load_string($return);
$ns = $return->getNamespaces(true);
foreach ($return->children($ns['ns2'])->category as $key) {
$data = $key->children();
echo $data->depth;
}