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.

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.

It will return html like this.

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.

How it works:

Instantiate DOMDocument class which allows you to work with HTML in a logical.

Load decoded HTML Content.

Get all images from the dom by getElementsByTagName.

Loop through each image and replace the src.

Get value of the src attribute from img tag.

Set the src attribute value in img tag.

Save the changes.

That’s it for today.
Thank you for reading. Happy Coding!

You may also like...

2 Responses

  1. Mohamad Md Som says:

    Thanks bro.. its works

Leave a Reply

Your email address will not be published. Required fields are marked *