如何从HTML代码中提取图像

时间:2014-07-24 14:42:03

标签: php html

我正在使用Magepierss从某些网址中提取Feed新闻我得到了标题,日期等。但不是图像,它存在于此字段[描述]中的html代码

[description] => <div style="margin: 5px 5% 10px 5%;"><img src="http://www.supermotoaustralia.com/wp-content/uploads/2014/07/showroom.jpg" width="90%" /></div><div>Australians purchased 53,396 new motorcycles, all-terrain vehicles (ATVs) and scooters in the first half of 2014, with road motorcycle purchases making up 40.6 per cent of these sales. While sales in the road motorcycle segment were up 2.2 per cent, total motorcycle, ATV and scooter sales were down 0.5 per cent compared to the same [&#8230;]</div>

并且我想在php中执行一个函数来exctrat这个html代码的图像 有任何想法吗 ?

4 个答案:

答案 0 :(得分:3)

或者作为替代方案,如果您考虑使用OOP方法而不是程序方法,您可以轻松地使用DomDocument类来浏览提供的DOM并使用其有用的方法。

一个例子:

$str = '<div style="margin: 5px 5% 10px 5%;"><img src="http://www.supermotoaustralia.com/wp-content/uploads/2014/07/showroom.jpg" width="90%" /></div><div>Australians purchased 53,396 new motorcycles, all-terrain vehicles (ATVs) and scooters in the first half of 2014, with road motorcycle purchases making up 40.6 per cent of these sales. While sales in the road motorcycle segment were up 2.2 per cent, total motorcycle, ATV and scooter sales were down 0.5 per cent compared to the same [&#8230;]</div>';

$dom = new DomDocument();
$dom->loadHTML($str);

$imgs = $dom->getElementsByTagName("img");

foreach ($imgs as $img) 
{
    var_dump($img->getAttribute('src'));
}

答案 1 :(得分:1)

你需要使用正则表达式。试试这个:

$str = '<div style="margin: 5px 5% 10px 5%;"><img src="http://www.supermotoaustralia.com/wp-content/uploads/2014/07/showroom.jpg" width="90%" /></div><div>Australians purchased 53,396 new motorcycles, all-terrain vehicles (ATVs) and scooters in the first half of 2014, with road motorcycle purchases making up 40.6 per cent of these sales. While sales in the road motorcycle segment were up 2.2 per cent, total motorcycle, ATV and scooter sales were down 0.5 per cent compared to the same [&#8230;]</div>';


$rx_main = '(<img src="(.+)")Ui';
preg_match($rx_main,$str,$result); 

print_r($result[1]);// will produce http://www.supermotoaustralia.com/wp-content/uploads/2014/07/showroom.jpg

答案 2 :(得分:0)

function get_srcs ( $string ) {

    static $matches;
    preg_match_all( '/<img.*?src.*?=.*?(?:\'")(.*?)\1/', $string, $matches );
    return array_column( $matches , 1 );

}

答案 3 :(得分:0)

创建正则表达式并使用preg_match()PHP函数来提取它。