vbd
vbd

Reputation: 3557

PHP DOM Xpath - how to get a single element

<?php
$html = new DOMDocument();
$html->loadHtmlFile( 'report.html' );
$xpath = new DOMXPath( $html );

$results = $xpath->evaluate('/html/body/div/table[2]/tr/td[3]');
foreach ($results as $result)
{
  {
    echo $result->nodeValue."\r\n";
  }
}
?> 

returns

GTkio94312
10/24/2011 10:21:45
01:19:46

I tried

echo $result->nodeValue->item[0];

to only get

GTkio94312

but it returns an empty line. Where's my fault?

Upvotes: 2

Views: 5978

Answers (1)

Marc B
Marc B

Reputation: 360662

->nodValue returns a simple string, not an object. Any given node has only a single nodeValue, so there's no ->item[...] subobject/subarray to retrieve other data from.

$results->item(0)->nodeValue;  // correct - nodevalue of first result node in results object
       ^---note the S
$result->item(0)->... // incorrect - result is a single node

xpath's query() returns a DOMNodeList. Doing a foreach on that list returns the individual DOMNode objects that were found by the xpath query. Each DOMNode has a single nodeValue attribute, which is the node's contents as a string.

Upvotes: 2

Related Questions