简体   繁体   English

php xml XPath foreach 返回所有节点而不是迭代

[英]php xml XPath foreach returning all nodes instead of iterating

I have a XML file like this我有一个像这样的 XML 文件

<Articles>
 <Article>
  <ArticleTitle> 
   First Book
 </ArticleTitle>
</Article>
 <Article>
  <ArticleTitle> 
   Second Book
 </ArticleTitle>
</Article>

And using this type of php script to retrieve the contents of ArticleTitle in an iterative fashion并使用这种类型的 php 脚本以迭代方式检索 ArticleTitle 的内容

foreach ($xml->Article as $Article){
$title = $Article->xpath('//ArticleTitle');
echo $title[0];
}

But this displays但这显示

First Book
First Book

Instead of代替

First Book
Second Book

I was assuming that when the foreach ($xml->Article as $Article) starts it will grab each Article node and then I can access the contents of that node but this is not what is happening.我假设当foreach ($xml->Article as $Article)启动时,它将抓取每个文章节点,然后我可以访问该节点的内容,但这不是正在发生的事情。 What am I doing wrong?我究竟做错了什么?

Your issue is that the xpath you have used is an absolute path (it starts with / ) so the fact that you are calling it from a child node has no effect.您的问题是您使用的 xpath 是绝对路径(以/开头),因此您从子节点调用它的事实无效。 You should use a relative path, in this case either simply ArticleTitle will suffice or .//ArticleTitle to allow for other nodes between Article and ArticleTitle .您应该使用相对路径,在这种情况下,简单的ArticleTitle就足够了,或者.//ArticleTitle允许ArticleArticleTitle之间的其他节点。 For example:例如:

foreach ($xml->Article as $Article){
    $title = $Article->xpath('ArticleTitle');
    echo $title[0];
}

foreach ($xml->Article as $Article){
    $title = $Article->xpath('.//ArticleTitle');
    echo $title[0];
}

Output in both cases is: Output 在这两种情况下都是:

First Book
Second Book

Demo on 3v4l.org 3v4l.org 上的演示

This should work too with your original XPath expression:这也应该适用于您原来的 XPath 表达式:

$xml = <<<'XML'
<Articles>
<Article>
<ArticleTitle>First Book</ArticleTitle>
</Article>
<Article>
<ArticleTitle>Second Book</ArticleTitle>
</Article>
</Articles>
XML;
$document = new DOMDocument();
$document->loadXML($xml);
$xpath = new DOMXpath($document);
$elements = $xpath->query('//ArticleTitle');
foreach($elements as $element)
echo ($element->nodeValue), "\n";
?>

Output: Output:

First Book
Second Book

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

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