How to extract images from external html page? – PHP

  php

Q(Question):

Ineed to extract images from html page using regular expression, but am not able to get desired result.
help me.
Bellow is my code

[PHP]<?php
$site=’http://www.gmail.com’;
$str_text = file_get_contents($site);

function str_img_src($html) {
if (strpos($html, ‘<img’) !== false) {
$imgsrc_regex = ‘#<\s*img [^\>]*src\s*=\s*(["\’])(.*?)\1#im’;
preg_match($imgsrc_regex, $html, $matches);
unset($imgsrc_regex);
unset($html);
if (is_array($matches) && !empty($matches)) {
return $matches;
} else {
return false;
}
} else {
return false;
}
}
$ms=str_img_src($str_text);
foreach($ms as $m) {
echo $m;
}

[/PHP]

A(Answer):

What results are you getting?
What aren’t you getting?
Please be more specific.

A(Answer):

If specified site contain an image within H1 tag then this code is able to return that image.
But i need to get path of all images and also want to copy/save those images.

A(Answer):

Try this pattern
"/<(img|IMG).*?(SRC|src)=\"(.*?)\"/"
If you use preg_match_all, you will receive all image paths in array index 3

A(Answer):

If specified site contain an image within H1 tag then this code is able to return that image.
But i need to get path of all images and also want to copy/save those images.

So… what happens with the code you use?

What output do you get?

A(Answer):

So… what happens with the code you use?

What output do you get?

I am getting first image (if it exist within h1 tag) otherwise it returns false.

A(Answer):

Try this pattern
"/<(img|IMG).*?(SRC|src)=\"(.*?)\"/"
If you use preg_match_all, you will receive all image paths in array index 3

Dear Rizwan,
I am still getting the same o/p.

LEAVE A COMMENT