您好谁能帮我如何从网页内容中选择特定的 div。
假设我想从 http://www.test.com/page3.php
网页获取带有 id="wrapper_content"
的 div。
我当前的代码看起来像这样:(不工作)
//REG EXP.
$s_searchFor = '@^/.dont know what to put here..@ui';
//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;
所以我想知道如何使用正则表达式来查找特定的 div 以及如何取消设置网页的其余部分以便 $file_content
只包含分区。
最佳答案
HTML isn't regular ,所以你不应该使用正则表达式。相反,我会推荐一个 HTML 解析器,例如 Simple HTML DOM或 DOM
如果您打算使用简单的 HTML DOM,您将执行如下操作:
$html = str_get_html($file_contents);
$elem = $html->find('div[id=wrapper_content]', 0);
即使您使用了正则表达式,您的代码仍然无法正常工作。在使用正则表达式之前,您需要获取页面的内容。
//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
关于php - 使用 CURL 从外部网页中选择特定的 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2559440/