2010-04-01 214 views
8

嗨,任何人都可以幫助我如何從網頁內容中選擇特定的div。使用CURL從外部網頁選擇特定的div

比方說,我想從網頁http://www.test.com/page3.php得到id="wrapper_content"的div。

我當前的代碼看起來是這樣的:(不工作)

//REG EXP. 
$s_searchFor = '@^/.dont know what to put [email protected]';  

//CURL 
$ch = curl_init(); 
$timeout = 5; // set to zero for no timeout 
curl_setopt ($ch, CURLOPT_URL, 'http://www.test.com/page3.php'); 
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout); 
if(!preg_match($s_searchFor, $ch)) 
{ 
    $file_contents = curl_exec($ch); 
} 
curl_close($ch); 

// display file 
echo $file_contents; 

所以,我想知道我可以使用reg表達式中找到特定的div以及如何未設置其餘該網頁使$file_content只包含div。

回答

14

HTML isn't regular,所以你不應該使用正則表達式。相反,我會推薦一個HTML解析器,例如Simple HTML DOMDOM

如果你要使用簡單HTML DOM,你會做類似如下:

$html = str_get_html($file_contents); 
$elem = $html->find('div[id=wrapper_content]', 0); 

即使你使用正則表達式您的代碼仍然止跌」 t正常工作。在使用正則表達式之前,您需要獲取頁面的內容。

//wrong 
if(!preg_match($s_searchFor, $ch)){ 
    $file_contents = curl_exec($ch); 
} 

//right 
$file_contents = curl_exec($ch); //get the page contents 
preg_match($s_searchFor, $file_contents, $matches); //match the element 
$file_contents = $matches[0]; //set the file_contents var to the matched elements 
+0

str_get_html()函數未定義。爲什麼? – huykon225 2017-08-23 09:53:46

0

檢查我們的角度來說,Hpricot,它可以讓你優雅地選擇部分

首先你會用捲曲來獲取文件,然後使用角度來說,Hpricot得到你需要

4
include('simple_html_dom.php'); 
$html = str_get_html($file_contents); 
$elem = $html->find('div[id=wrapper_content]', 0); 

下載simple_html_dom.php

部分