user7962781
user7962781

Reputation:

How to retrieve OUTSIDE the "foreach" loop of my PHP Code, the VERY FIRST image of the page?

With DomDocument and knowing that the variable $img_wiki_collected_src which represents the links or the URL of each image of the page, I try to collect OUTSIDE THE foreach, the very first image of the Page but that does not work when I do echo $img_wiki_collected_src (outside the foreach loop), instead it's the URL of the last image on the page that's displayed instead of the first image I'm looking to to display.

libxml_use_internal_errors(true);
$parser = new DOMDocument();
$parser->loadHTMLFile("https://fr.wikipedia.org/wiki/Alibaba_Group");
$get_img_tags = $parser->getElementsByTagName("img");
foreach($get_img_tags as $img_collected) {
    $img_wikiped_src = $img_collected->getAttribute("src");
    $img_wiki_collected_src = createLink($img_wikiped_src, $url);
    $img_collected->setAttribute('src', $img_wiki_collected_src);
}

How then, to display OUTSIDE THE foreach, the URL of THE VERY FIRST IMAGE of the page knowing once again that it is the variable $img_wiki_collected_src which represents the link of each image of the page using the loop foreach ?

How to display out of the foreach loop the first image of the page ?

Thank you please help me.

Upvotes: 0

Views: 27

Answers (2)

user7962781
user7962781

Reputation:

Thanks everyone for yor answer. But, I get the following error:

Fatal error: Uncaught TypeError: array_values() expects parameter 1 to be array, object given in C:\laragon\www\test.php:239 Stack trace: #0 C:\laragon\www\test.php(239): array_values(Object(DOMNodeList)) #1 {main} thrown in C:\laragon\www\test.php on line 239

When I do:

libxml_use_internal_errors(true);
$parser = new DOMDocument();
$parser->loadHTMLFile("https://fr.wikipedia.org/wiki/Alibaba_Group");
$get_img_tags = $parser->getElementsByTagName("img");
$first_image_colected_src = createLink(array_values($get_img_tags)[0]->getAttribute("src"));
foreach($get_img_tags as $img_collected) {
    $img_wikiped_src = $img_collected->getAttribute("src");
    $img_wiki_collected_src = createLink($img_wikiped_src, $url);
    $img_collected->setAttribute('src', $img_wiki_collected_src);
}

echo $first_image_colected_src;

So, It doesn't work.

Help please.

Upvotes: 0

kissumisha
kissumisha

Reputation: 493

Try this just before the foreach loop:

$first_image_src = $get_img_tags[0]->getAttribute("src");

Upvotes: 1

Related Questions