How to get all image tags from an html - php code

August 20, 2017

Problem Statement

I wanted to fetch all image tags from a big html, and wanted to perform some check on the ’src’ value of img tag. This blog is about how I did that.


See the code below:

$doc = new DOMDocument();
$tags = $doc->getElementsByTagName('img');
$imgArr = array();

//iterate over all image tags
foreach ($tags as $tag) {
  //get src attribute of an img tag
  $imgSrc = $tag->getAttribute('src');

  //Do your processing with any attribute of img tag

Sample Output

Similar Posts

Latest Posts