简体   繁体   English

循环遍历元素子元素

[英]looping through elements sub-elements

I am trying to extract data from a structure that looks like http://chris.photobooks.com/xml/default.htm?state=8T 我试图从一个看起来像http://chris.photobooks.com/xml/default.htm?state=8T的结构中提取数据

using the following function I am trying to loop through every product tag 使用以下函数我试图遍历每个产品标签

$dom = new DOMDocument;
$dom->loadXML($resp);
$xpath = new DOMXPath($dom);
$xpath->registerNamespace('ns2', 'http://mws.amazonservices.com/schema/Products/2011-10-01/default.xsd');
$xpath->registerNamespace('a', 'http://mws.amazonservices.com/schema/Products/2011-10-01');

foreach($xpath->query('//a:Product') as $product){
    echo $product->query('//ns2:ItemAttributes/ns2:Author')->item(0)->nodeValue
}

I now realize that this is the wrong way to extract data from within the for loop, but what is the correct way? 我现在意识到这是从for循环中提取数据的错误方法,但正确的方法是什么?

If you need specific tags, you can do: 如果您需要特定标签,您可以:

$dom = new DOMDocument;
$dom->loadXML($resp);

foreach($dom->getElementsByTagName("Product") as $product){
    echo $product->getElementsByTagName("Author")->item(0)->nodeValue."<br />";
}

Otherwise (if you need the whole data) there are community-made solutions for converting the whole XML into a simple array/object. 否则(如果您需要整个数据)有社区制作的解决方案,用于将整个XML转换为简单的数组/对象。

I think you want 我想你想要的

foreach($xpath->query('//a:Product') as $product){
    echo $xpath->query('.//ns2:ItemAttributes/ns2:Author', $product)->item(0)->textContent
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM