Pulling text and attribute of a given node using Xpath

I am parsing XML results from an API call using PHP and xpath.

 $dom = new DOMDocument();
 $dom->loadXML($response->getBody());

 $xpath = new DOMXPath($dom);
 $xpath->registerNamespace("a", "http://www.example.com");

 $hrefs = $xpath->query('//a:Books/text()', $dom);

 for ($i = 0; $i < $hrefs->length; $i++) {
      $arrBookTitle[$i] = $hrefs->item($i)->data;
 }

 $hrefs = $xpath->query('//a:Books', $dom);

 for ($i = 0; $i < $hrefs->length; $i++) {
      $arrBookDewey[$i] = $hrefs->item($i)->getAttribute('DeweyDecimal');
 }

This works, but is there a way to access both the text and the attribute from a single request? And if so, how do you get to these elements after completing the request?

+5
source share
4 answers

After looking around a bit, I came across this solution. This way I can get the text of the element and access any node attributes.

$hrefs = $xpath->query('//a:Books', $dom);

for ($i = 0; $i < $hrefs->length; $i++) {
    $arrBookTitle[$i] = $hrefs->item($i)->nodeValue;
    $arrBookDewey[$i] = $hrefs->item($i)->getAttribute('DeweyDecimal');
}
+4
source

The only XPath expression that will select both the text nodes "a: Books" and their attribute "DeweyDecimal" is as follows

//a:Books/text() | //a:Books/@DeweyDecimal

XPath .

: "//", XML , , . XPath (, ), XML.

+3

XML-, SimpleXML , :

$xml=simplexml_load_string($response->getBody());
$xml->registerXPathNamespace('a', 'http://www.example.com');
$books=$xml->xpath('//a:Books');
foreach ($books as $i => $book) {
    $arrBookTitle[$i]=(string)$book;
    $arrBookDewey[$i]=$book['DeweyDecimal'];
}
+2

?

$xpath->query('concat(//a:Books/text(), //a:Books/@DeweyDecimal)', $dom);

XSLT , - .

0
source

All Articles