应该如何解析PHP(简单的html dom解析器)背景图像和其他网页图像?

时间:2010-07-10 19:26:25

标签: php parsing html-parsing simple-html-dom

如何解析PHP(简单的html dom / etc ..)背景和其他网页图片?

案例1:内联css

<div id="id100" style="background:url(/mycar1.jpg)"></div>

案例2:html页面内的CSS

<div id="id100"></div>

<style type="text/css">
#id100{
background:url(/mycar1.jpg);
}
</style>

案例3:单独的css文件

<div id="id100" style="background:url(/mycar1.jpg);"></div>

external.css

#id100{
background:url(/mycar1.jpg);
}

案例4:img标签内的图片

解决案例4 ,因为他出现在php simple html dom parser

// Create DOM from URL or file
$html = file_get_html('http://www.google.com/');

// Find all images
foreach($html->find('img') as $element)
       echo $element->src . '<br>';

请帮我解析案例1,2,3。

如果存在更多案例,请写下它们,如果可以的话请解决。

由于

2 个答案:

答案 0 :(得分:2)

案例1:

// Create DOM from URL or file 
$html = file_get_html('http://www.google.com/');

// Get the style attribute for the item
$style = $html->getElementById("id100")->getAttribute('style');

// $style = background:url(/mycar1.jpg)
// You would now need to put it into a css parser or do some regular expression magic to get the values you need.

案例2/3:

// Create DOM from URL or file
$html = file_get_html('http://www.google.com/');

// Get the Style element
$style = $html->find('head',0)->find('style');

// $style now contains an array of style elements within the head. You will need to work out using attribute selectors what whether an element has a src attribute, if it does download the external css file and parse (using a css parser), if it doesnt then pass the innertext to the css parser.

答案 1 :(得分:1)

要从页面中提取<img>,您可以尝试以下内容:

$doc = new DOMDocument(); 
$doc->loadHTML("<html><body>Foo<br><img src=\"bar.jpg\" title=\"Foo bar\" alt=\"alt\"></body></html>"); 
$xml = simplexml_import_dom($doc);
$images = $xml->xpath('//img'); 
foreach ($images as $img) 
    echo $img['src'] . ' ' . $img['alt'] . ' ' . $img['title']; 

有关详细信息,请参阅DOMDocument的文档。