How to get only the first result from getElementsByTagName?

Tonny Struck picture Tonny Struck · Aug 7, 2013 · Viewed 8.1k times · Source

Hi there i am using the code to get the adress of all images from url adress. I want to ask how i can get only the first result not all matches?

Here is the code that i am using:

<?php


$url="http://grabo.bg/relaks-v-pamporovo-0gk5b";

$html = file_get_contents($url);

$doc = new DOMDocument();
@$doc->loadHTML($html);

$tags = $doc->getElementsByTagName('img');

foreach ($tags as $tag) {
   echo $tag->getAttribute('src');
}

?>

So please tell me how i can get only one result - the first!

Thanks in advance.

Answer

defaultNINJA picture defaultNINJA · Aug 7, 2013

$tags is a DOMNodeList object created by the DOMDocument's getElementsByTagName method. So you can access the first element returned with DOMNodelist::item ( int $index ).

For your code do: $tags->item(0);