Search code examples
phpdomxpath

DOMXPath get first value of query


considering you're searching just one specific value is there to get the only and first result directly without parsing the result with foreach? Like this:

$elements = $dom_xpath->query('//span[@id="loginName"]');


echo $elements->firstNode->nodeValue; // this doesn't exist of course

the html code is

<div>
  <div id="name">text<span id="loginName">Me</span></div>
</div>

Solution

  • If you are sure there will be a match, you can use

    echo $dom_xpath->query('//span[@id="loginName"]')->item(0)->nodeValue;