Chris Jones
Chris Jones

Reputation: 415

replace img src with php

I would like to take a block of code stored in a variable and replace the src of any image tags in there without disturbing the rest of the code block.

For example : the block of code might read :

<a href="http://mylink.com"><img src="image1.jpg"></a>

I would like to change that to (using PHP) :

<a href="http://mylink.com"><img src="altimage.jpg"></a>

I am currently using a solution I found using the PHP DOM module to change the image tag but the function returns just the changed img tag HTML without the rest of the HTML.

The function I am calling is as follows :

function replace_img_src($original_img_tag, $new_src_url) {
    $doc = new DOMDocument();
    $doc->loadHTML($original_img_tag);
$tags = $doc->getElementsByTagName('img');
if(count($tags) > 0)
{
       $tag = $tags->item(0);
       $tag->setAttribute('src', $new_src_url);
       return $doc->saveXML($tag);
}

return false;
}

This, of course, just returns the changed img tag but strips the other HTML (such as the A tag) - I am passing the entire block of code to the function. (BTW - It's good for me to have the false return for no image tags as well).

What am I missing here please ?

Many thanks in advance for any help.

Upvotes: 2

Views: 2928

Answers (1)

ByteHamster
ByteHamster

Reputation: 4951

You need to use return $doc->saveXML(); instead of return $doc->saveXML($tag);. See the documentation of saveXML:

saveXML ([ DOMNode $node [, int $options ]] )

node: Use this parameter to output only a specific node without XML declaration rather than the entire document.

Upvotes: 2

Related Questions