php - 使用 CURL 从外部网页中选择特定的 div

标签 php regex html curl

您好谁能帮我如何从网页内容中选择特定的 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 DOMDOM

如果您打算使用简单的 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/

相关文章:

javascript - 使用正则表达式从解析的 HTML 中获取值

java - libGDX html :draftCompileGwt Compilation Error

php - 如何使用 TEXT 类型字段在 MySQL 上获得快速性能?

php删除数组中的 "empty"值

php - 使用PHP显示curl结果

javascript - 正则表达式 : Retrieve the GUID inside [ ] parenthesis

regex - 删除R中两种字符串模式之间的字母

javascript - 允许周围div的点击事件仅在未点击内部标签时触发

css - html5 按钮背景图像状态

php - 将网页导出为 PDF(使用 PHP)