4

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.

Tonny Struck
  • 247
  • 4
  • 9
  • 17
  • 1
    [`$xpath->evaluate('string(//img[1]/@src)')`](http://stackoverflow.com/questions/7464092/xpath-get-single-value-returned-instead-of-array-php/7464905#7464905) – Gordon Aug 07 '13 at 13:02
  • @Gordon How is XML evaluation the same as accessing the first HTML element? Think you're confused on what the OP asked. – Iron3eagle Aug 07 '13 at 13:23
  • @defaultNINJA the OP wants to get only the first result, so apparently he is after the first img src value and that's what the XPath does. It's just a different way to the same result as doing `$doc->getElementsByTagName('img')->item(0)->getAttribute('src');` Note that the dupe is an exact dupe of this one and not the one linked in my comment. – Gordon Aug 07 '13 at 13:26
  • @Gordon Gotcha, see it now, thanks! – Iron3eagle Aug 07 '13 at 13:27

3 Answers3

8

$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);

Iron3eagle
  • 1,077
  • 7
  • 23
  • I don't get it where i must put this `$tags->item(0);` and what i have to remove? – Tonny Struck Aug 07 '13 at 13:12
  • @TonnyStruck where ever it is you need to access the first element in your code. `$tags->item(0);` is the first element. So you could do `$firstElem = $tags->item(0);` and just access that variable when you need too. – Iron3eagle Aug 07 '13 at 13:22
0

Be careful some browsers chose to return HTMLCollection instead, which is OK, since it is a superset of NodeList.
See Difference between HTMLCollection, NodeLists, and arrays of objects

Community
  • 1
  • 1
SGh
  • 137
  • 1
  • 2
  • 9
-1

Use:

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

To get the first element in the array.

Tdelang
  • 1,298
  • 2
  • 12
  • 20