2010-07-10 15 views
1

如何解析與PHP(簡單的HTML DOM /等..)背景和其他圖像的網頁?如何解析PHP(簡單的HTML DOM解析器)背景圖片和其他網頁圖片?

殼體1:內嵌CSS

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

殼體2:單獨的CSS文件

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

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

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

殼體3內的CSS

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。

如果存在更多的情況,請寫下來,如果可以的話請聯繫我們。

感謝

+0

掌握像DOM庫內容進行HTML文件(包括今天)之前已經回答了無數次。外部CSS文件不能由SGML/XML庫處理。另請注意,節點內容只是這些庫的字符數據。如果要將內容解析爲CSS,則必須找到其他解析器。 – Gordon 2010-07-10 19:48:05

回答

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

要從你可以嘗試類似的網頁中提取<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瞭解更多詳情。

+0

DOMElement implements /允許ArrayAccess? – Gordon 2010-07-10 19:37:09

+0

我已經編寫了img標籤的解決方案我的答案只適用於背景css圖像 – Yosef 2010-07-10 19:47:08