Home > Mobile >  How to retrieve OUTSIDE the "foreach" loop of my PHP Code, the VERY FIRST image of the pag
How to retrieve OUTSIDE the "foreach" loop of my PHP Code, the VERY FIRST image of the pag

Time:06-11

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.

CodePudding user response:

Try this just before the foreach loop:

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

CodePudding user response:

Just modifiing answer from @kissumisha:

$first_image_colected_src = createLink(array_values($get_img_tags)[0]->getAttribute("src"));

it should be also protected against empty array (in case that page doesn't contain any image) with if(!empty($get_img_tags))...

CodePudding user response:

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.

  • Related