【问题标题】:Looping through XML with namespace PHP使用命名空间 PHP 循环 XML
【发布时间】:2017-04-10 02:30:20
【问题描述】:

我有一个这样的 xml curl 响应:

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

我尝试使用以下代码获取&lt;ns2:category&gt; 中的数据:

$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
(
)

【问题讨论】:

    标签: php xml curl


    【解决方案1】:

    您需要在循环数据之前将getNamespaces 设置为true,并且在循环内您需要调用子函数以便它获取数据并将其包装在对象变量中

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

    【讨论】:

      猜你喜欢
      • 2019-08-31
      • 2021-07-21
      • 2012-06-11
      • 2013-04-30
      • 1970-01-01
      • 2010-11-17
      • 2015-12-06
      • 1970-01-01
      相关资源
      最近更新 更多