cod*_*ird 3 php xpath curl dom
我正在创建一个小的网络应用程序来帮助我管理和分析我的网站内容,而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 = $iframes->item($i);
$framesrc = $iframe->getAttribute("src");
$framewidth = $iframe->getAttribute("width");
$frameheight = $iframe->getAttribute("height");
$framealt = $iframe->getAttribute("alt");
$frameclass = $iframe->getAttribute("class");
$info .= $framesrc.' ('.$framewidth.'x'.$frameheight.'; class="'.$frameclass.'")'.'<br />';
}
Run Code Online (Sandbox Code Playgroud)
问题/问题:
如何提取HTML评论?
我无法弄清楚如何识别评论 - 它们被认为是节点还是完全不同的东西?
如何获取div的整个内容,包括子节点?因此,如果div包含一个图像和几个href,它会找到这些并将它作为一个HTML块交给我.
lon*_*day 13
使用comment()
测试在XPath中很容易找到注释节点,类似于text()
测试:
$comments = $xpath->query('//comment()'); // or another path, as you prefer
Run Code Online (Sandbox Code Playgroud)
它们是标准节点:这是DOMComment
该类的手动输入.
对于你的另一个问题,它有点棘手.最简单的方法是使用saveXML()
其可选$node
参数:
$html = $dom->saveXML($el); // $el should be the element you want to get
// the HTML for
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3937 次 |
最近记录: |