Pau*_*aul 9 html php regex curl
大家好,任何人都可以帮我如何从网页内容中选择一个特定的div.
假设我想id="wrapper_content"从网页 获取div http://www.test.com/page3.php.
我当前的代码看起来像这样:(不工作)
//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;
Run Code Online (Sandbox Code Playgroud)
所以我想知道如何使用reg表达式来查找特定的div以及如何取消设置网页的其余部分,以便$file_content只包含div.
Yac*_*oby 15
HTML不常规,因此您不应使用正则表达式.相反,我会推荐一个HTML解析器,如简单的HTML DOM或DOM
如果您打算使用Simple HTML DOM,您可以执行以下操作:
$html = str_get_html($file_contents);
$elem = $html->find('div[id=wrapper_content]', 0);
Run Code Online (Sandbox Code Playgroud)
即使您使用正则表达式,您的代码仍然无法正常工作.在使用正则表达式之前,您需要获取页面的内容.
//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
Run Code Online (Sandbox Code Playgroud)