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.

4
  • 1
    $xpath->evaluate('string(//img[1]/@src)')
    – Gordon
    Commented Aug 7, 2013 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
    Commented Aug 7, 2013 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
    Commented Aug 7, 2013 at 13:26
  • @Gordon Gotcha, see it now, thanks!
    – Iron3eagle
    Commented Aug 7, 2013 at 13:27

3 Answers 3

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

2
  • I don't get it where i must put this $tags->item(0); and what i have to remove? Commented Aug 7, 2013 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
    Commented Aug 7, 2013 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

3
  • OP is not in a browser. DOM is a language agnostic interface.
    – Gordon
    Commented Aug 7, 2013 at 13:07
  • I have made it. Can you please tell me how i make it start indexing from the thrird result to the end ? Commented Aug 7, 2013 at 15:16
  • Try this echo $tags->item(0)->getAttribute('src'); . It's work for me.
    – SGh
    Commented Aug 8, 2013 at 7:10
-1

Use:

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

To get the first element in the array.

2
  • 1
    $tags is not an array, but a DOMNodeList and it doesn't implement ArrayAccess
    – Gordon
    Commented Aug 7, 2013 at 13:05
  • It's not working Parse error: syntax error, unexpected '[' in /home/superweb/public_html/maxoferti/test.php on line 12 Commented Aug 7, 2013 at 13:05

Not the answer you're looking for? Browse other questions tagged or ask your own question.