Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Only the first result of a DOM xPath query

Tags:

dom

php

xpath

Let's say I have this code:

$dom = new DOMDocument();
@$dom->loadHTMLFile('sample.html');
$xp = new DOMXPath($dom);
$result = $xp->query("//input[@id='honey']");

How do I get the content of the attribute value of the first result only, since I'm only expecting one result (without using a foreach loop). I tried var_dump-ing the result but it can't. I also tried current($result)->getAttribute('value') but not luck.

like image 695
Jürgen Paul Avatar asked Jan 22 '12 02:01

Jürgen Paul


People also ask

How do you select the first occurence of XPath?

Simplified Xpath syntax:/e1 -- selects the first <e1> document element (child element of the document node). /e1/e2 -- selects the first <e2> child element of the first <e1> document element. /e1[2]/e2[3] -- selects the third <e2> child element of the second <e1> document element. /e1[1]/e2[1] -- same as /e1/e2 .

Is XPath faster than DOM?

As the answer in xPath vs DOM API, which one has a better performance says, average programmer may screw up when implementing complicated tasks (e.g. multiple axes involved) in DOM way while XPath is guaranteed optimized.

Does XPath use DOM?

The XML Document Object Model (DOM) contains methods that allow you to use XML Path Language (XPath) navigation to query information in the DOM. You can use XPath to find a single, specific node or to find all nodes that match some criteria.

What is DOM in XPath?

The DOM model uses Element nodes to represent Element Information Items. These nodes of a document are directly used to represent the elements of an XPath result.


2 Answers

You can access it via the following method:

$value = $result->item(0)->attributes()->getNamedItem("value")->nodeValue;
like image 64
Tim Cooper Avatar answered Sep 28 '22 02:09

Tim Cooper


Just evaluate this XPath expression:

(//input[@id='honey'])[1]/@value

This selects the attribute value of the first input element in the XML document, the string value of whose id attribute is "honey".

If you want to get not the value attribute, but its string value, use:

string((//input[@id='honey'])[1]/@value)
like image 27
Dimitre Novatchev Avatar answered Sep 28 '22 02:09

Dimitre Novatchev