Get all images from a HTML document Using PHP

Dec 13, 2013, by admin

Sometimes we have to get the images from an HTML page just like Facebook does when a link is posted. You can easily get images from HTML page using PHP. Below example code will return all images from a HTML document, you just need to get the source content of any HTML page and pass through below PHP function.

 

  1. <?php
  2. function getImagesFromHTMLDocument($data)
  3. {
  4. $images = array();
  5. preg_match_all(‘/<img [^>]*src=[“|’]([^”|’]+)/i’, $data, $matches);
  6. foreach ($matches[1] as $key=>$value) {
  7. $info = pathinfo($value);
  8. if (isset($info[‘extension’]))
  9. {
  10. if (($info[‘extension’] == ‘jpg’) ||
  11. ($info[‘extension’] == ‘jpeg’) ||
  12. ($info[‘extension’] == ‘gif’) ||
  13. ($info[‘extension’] == ‘png’))
  14. array_push($images, $value);
  15. }
  16. }
  17. return $images;
  18. }
  19. $img=getImagesFromHTMLDocument($data);
  20. print_r($img);
  21. ?>

To get more updates like the page Bugtreat Technologies and like the page Cs Cart Template for our Template updates