Replace image src in HTML using PHP
Today we will show you how to replace image src in HTML using PHP.
How to replace image src in a dynamic HTML string with PHP, PHP: How to replace dynamic src of an image, Dynamically replace the “src” attributes of all tags, How to set html img src from code behind, How To Dynamically Change Image Src Example.
Checkout more articles on PHP
Sometimes we need to change the image src attribute with new url when dynamically getting data from the database.
Assume that we will get html content in product description from the database using below php code.
1 | $data['description']=html_entity_decode($productData['description'],ENT_QUOTES,'UTF-8'); |
It will return html like this.
1 2 3 4 | <span> Product Name 1 <span> <a href="#"><img src="../images/products/image1.jpg"></a> <span> Product Name 2 <span> <a href="#"><img src="../images/products/image2.jpg"></a> |
Many images can be in product description but I have taken 2 images in our example.
Here we will replace src attribute of every image and add new attribute data-src with old image url.
1 2 3 4 5 6 7 8 9 10 11 12 | $dom = new DOMDocument(); $dom->loadHTML($data['description']); $images = $dom->getElementsByTagName('img'); foreach ($images as $image) { $old_src = $image->getAttribute('src'); $new_src = 'image/products/newimage.jpg'; $image->setAttribute('src', $new_src); $image->setAttribute('data-src', $old_src); } $data['description'] = $dom->saveHTML(); |
How it works:
Instantiate DOMDocument
class which allows you to work with HTML in a logical.
1 | $dom = new DOMDocument(); |
Load decoded HTML Content.
1 | $dom->loadHTML($data['description']); |
Get all images from the dom by getElementsByTagName
.
1 | $images = $dom->getElementsByTagName('img'); |
Loop through each image and replace the src
.
Get value of the src
attribute from img
tag.
1 | $image->getAttribute('src'); |
Set the src attribute value in img tag.
1 | $tag->setAttribute('src', $new_src); |
Save the changes.
1 | $dom->saveHTML(); |
That’s it for today.
Thank you for reading. Happy Coding!
Thanks bro.. its works
Thanks for following us. Like & Share it. Happy Coding..!!!