0

I am using this below code to get the elements that are in special HTML element :

$dom = new DOMDocument();
@$dom->loadHTML($google_html);
$xpath = new DOMXPath($dom);
$tags = $xpath->query('//span[@class="st"]');    
foreach ($tags as $tag) {
    echo $node_value;
}

Now, the problem is that, the code gives all of the elements that are in one special class, but i just need to get the First item that has that class name.

So i don't need using foreach loops.

How to use that code to get JUST the FIRST item ?

Cab
  • 121
  • 1
  • 1
  • 12

1 Answers1

2

The following will make sure you get just the first one in the DOMNodeList that is returned

$xpath->query('//span[@class="st"][1]');

The following gets the only item in the DOMNodeList

$tags = $xpath->query('//span[@class="st"][1]');
$first = $tags->item(0);
$text = $first->textContent;

See XPath: Select first element with a specific attribute

Community
  • 1
  • 1
Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
  • tnx, but the error : (( Object of class DOMNodeList could not be converted to string in )) + Your code need to be closed with `'` and `)`. any way, not worked ! – Cab Jul 22 '14 at 18:13
  • 1
    @Cab I've updated my answer, you need to get the first item, a [`DOMNode`](http://php.net/manual/en/class.domnode.php), then you need to access whatever property you're looking for – Ruan Mendes Jul 22 '14 at 18:16
  • Tnx alot . Worked perfectly :X – Cab Jul 22 '14 at 18:20