Get SRC attribute value of an image inside the DIV

Asked

Viewed 160 times

-1

I have a div that has a registered image and the problem is this: only this div tag that has id through this div id I need to know the address of the image that is in src.

Example:

<div id="output"> <img src="/images/blog/outra-imagem-C.jpg" /> </div>

That is, I search for id="output" and it returns the address src="/images/blog/client-ideal-Voce-sabe-quem-e.jpg".

I tried using Domdocument

$dom = new DOMDocument();
$dom->loadHTML($data);

$img = $dom->getElementById("output");

echo $img->getAttribute("src"), PHP_EOL;

But without success because it should use the

getElementByTagName with IMG

But I need to get it through the ID of the DIV.

Note: Accepted solution in PHP.

  • Why PHP? Should this check be run on the server? What do you need to do with this image?

  • Yes, you said that in the question, but why do you need the solution in PHP? What will justify using this language? What you need to do with this value that justifies doing this on the server?

  • Ué, gave up that it could be in Javascript too?

  • @Andersoncarloswoss replied based on the tag I saw in the first issue, I didn’t even see if there were any others due to some quick issues not appearing :)

  • @Guilhermenascimento He had commented that it could be in JS when I questioned what would justify using PHP. It seems that he deleted the comment.

1 answer

0


You are trying to get the DIV src and not the image, if the getElementById returns the DIV element, so you have to run in the DIV context getElementsByTagName('img'), so it will take any descending element that is of the type <img>, being like this:

$dom = new DOMDocument();
$dom->loadHTML($data);

$divOutput = $dom->getElementById("output");

foreach ($divOutput->getElementsByTagName('img') as $el) {
    var_dump( $el->getAttribute('src') );
}

To catch only the first occurrence just use an IF, so:

$dom = new DOMDocument();
$dom->loadHTML($data);

$divOutput = $dom->getElementById("output");

if (!$divOutput) {
    echo '#output não encontrado';
} else {
    $imgs = $divOutput->getElementsByTagName('img');

    if (!$imgs->length) {
         echo 'Não há imagens dentro de #output';
    } else {
         var_dump( $imgs[0]->getAttribute('src') );
    }
}

The $imgs[0] will take only the first occurrence.

  • Perfect!!!!!!!!!!!!!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.