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.
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 .
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.
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.
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.
You can access it via the following method:
$value = $result->item(0)->attributes()->getNamedItem("value")->nodeValue;
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With