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
- Send an email using PHP mail() function
- Add or Subtract days, month and year to a date using PHP
- Sorting Arrays in PHP
- Remove the last character from a string in 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.
$data['description']=html_entity_decode($productData['description'],ENT_QUOTES,'UTF-8');
It will return html like this.
<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.
$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.
$dom = new DOMDocument();
Load decoded HTML Content.
$dom->loadHTML($data['description']);
Get all images from the dom by `getElementsByTagName`.
$images = $dom->getElementsByTagName('img');
Loop through each image and replace the `src`.
Get value of the `src` attribute from `img` tag.
$image->getAttribute('src');
Set the src attribute value in img tag.
$tag->setAttribute('src', $new_src);
Save the changes.
$dom->saveHTML();
That’s it for today.
Thank you for reading. Happy Coding!