开发者

fetch all images src into array with file get content

i have the following function for getting images...

function getImages($content){
    $regex = '/<img src=\"([^\"]*)(")/iU';
    preg_match_all($regex,$content,$match);
    var_dump($match);
    return $match[0];
}

and here i am calling it...

$link = "http://mydomain.com";
$content = file_get_contents($link);
$img = getImages($content);
echo $img;

it is working all the way fine but the problem is that it shows me a lot of text along with images like

array(3) { [0]=> array(27) { [0]=> string(37)
tring(106) "http://cdn3.diggstatic.com/story/reddit_open_to_chat_over_ben_cheezburger_huh_s_proposed_acquisition/t.png" } [2]=> array(27) { [0]=> string(1) """ [1]=> string(1) """ [2]=> string(1) """ [3]=> string(1) """ [4]=> string(1) """ [5]=> string(1) """ [6]=> string(1) """ [7]=> string(1) """ [8]=> string(1) """ [9]=> string(1) """ [10]=> string(1) """ [11]=> string(1) """ [12]=> string(1) """ [13]=> string(1) """ [14]=> string(1) """ [15]=> string(1) """ [16]=> string(1) """ [17]=> string(1) """ [18]=> string(1) """ [19]=> string(1) """ [20]=> string(1) """ [21]=开发者_运维知识库> string(1) """ [22]=> string(1) """ [23]=> string(1) """ [24]=> string(1) """ [25]=> string(1) """ [26]=> string(1) """ } }

while i only want to get images...how can i remove all that text and get all images


Dont use regex to extract tags from a html document, try the PHP dom extension:

function getImages($content) {
    $doc = new DOMDocument(); 
    $doc->loadHTML($content);
    $imgElements = $doc->getElementsByTagName('img');

    $images = array();

    for($i = 0; $i < $imgElements->length; $i++) {
        $images[] = $imgElements->item($i)->getAttribute('src');
    }

    return $images;
}

// usage: 
$content = file_get_contents('http://www.example.com/');
$images = getImages($content);

print_r($images);


Remove the var_dump($match); from the getImages function.

And, if you get absolutely no output after doing so, change echo $img; to echo $img[0];

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜