我正在创建一个小的网络应用程序来帮助我管理和分析我的网站内容,而cURL是我最喜欢的新玩具.我已经想出如何提取有关各种元素的信息,如何查找具有某个类的所有元素等,但我遇到了两个问题(见下文).我希望有一些漂亮的xpath答案,但如果我不得不诉诸正则表达式,我猜这没关系.虽然我对正则表达式不是那么好,所以如果你认为这是要走的路,我会欣赏这些例子......
相当标准的起点:
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$html = curl_exec($ch);
if (!$html) {
$info .= "<br />cURL error number:" .curl_errno($ch);
$info .= "<br />cURL error:" . curl_error($ch);
return $info;
}
$dom = new DOMDocument();
@$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
Run Code Online (Sandbox Code Playgroud)
和提取信息,例如:
// iframes
$iframes = $xpath->evaluate("/html/body//iframe");
$info .= '<h3>iframes ('.$iframes->length.'):</h3>';
for ($i = 0; $i < $iframes->length; $i++) {
// get iframe attributes
$iframe …Run Code Online (Sandbox Code Playgroud)