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.

Solution

See the code below:

$doc = new DOMDocument();
$doc->loadHTML($body);
$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

https://st.hzcdn.com/simgs/08611ef0050cb085_8-4061/contemporary-bathroom.jpg
https://st.hzcdn.com/simgs/f5c19084044862df_8-4100/modern-bathroom.jpg
https://st.hzcdn.com/simgs/db21d41901d3cc2d_8-7242/contemporary-bathroom.jpg
https://st.hzcdn.com/simgs/dbf10837069daa21_8-1951/contemporary-bathroom.jpg
https://st.hzcdn.com/simgs/e8e1de0e0231e294_8-8943/contemporary-bathroom.jpg
https://st.hzcdn.com/simgs/8c71b1fe0535cbe3_8-8313/contemporary-bathroom.jpg
https://st.hzcdn.com/simgs/e961a3e003fd7b05_8-4430/contemporary-bathroom.jpg
https://st.hzcdn.com/simgs/1ef1a9660cda6923_8-3728/contemporary-bathroom.jpg

Similar Posts

Latest Posts