1

I have a XML file like this

<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

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. What am I doing wrong?

2 Answers 2

3

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

First Book
Second Book

Demo on 3v4l.org

Sign up to request clarification or add additional context in comments.

Comments

1

This should work too with your original XPath expression :

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

First Book
Second Book

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.