2012-06-07 38 views
3

我可以得到源代碼很好,但我現在希望能夠從一個特定專區內獲取數據:PHP獲取html源代碼,那麼一定DIV標籤內的解析值

$html = file_get_contents('http://www.website.com'); 

說$ html包含:

<div class="productData"> 
    <div class="productDescription">Here is the product description</div> 
    <div class="productPrice">1.99</div> 
</div> 

我希望能夠返回內的數據,並對所有事件做到這一點?

謝謝。

回答

2

使用DOMDocument class,與DOMXPath相結合,這樣的事情:

$url = 'http://www.website.com/'; 
$dom = new DOMDocument(); 
$dom->load($url); 
$xpath = new DOMXPath($dom); 
$nodes = $xpath->query("//*[contains(@class, 'productData')]"); 
foreach ($nodes as $node) { 
    // do something 
} 
+0

做這一點,或使用'preg_match'功能匹配字符串和操縱 –

+4

沒有,[不這樣做(HTTP:// www.codinghorror.com/blog/2009/11/parsing-html-the-cthulhu-way.html)! – Jeroen

+0

我嘗試了這些方法,但是我得到了這個: '警告:DOMDocument :: loadHTML()[domdocument.loadhtml]:意外的結束標記:實體頭部 – ashfp