【发布时间】:2011-08-17 17:10:25
【问题描述】:
可能的重复:
Get title of website via link
How do I extract title of a website?
如何使用 PHP DOM 抓取网站的标题? (使用 PHP 获取它的最佳方式是什么?)
【问题讨论】:
可能的重复:
Get title of website via link
How do I extract title of a website?
如何使用 PHP DOM 抓取网站的标题? (使用 PHP 获取它的最佳方式是什么?)
【问题讨论】:
您可以使用 getElementByTagName(),因为从技术上讲,您的 html 中只有一个标题属性,因此您可以抓住在 DOM 中遇到的第一个属性。
$title = '';
$dom = new DOMDocument();
if($dom->loadHTMLFile($urlpage)) {
$list = $dom->getElementsByTagName("title");
if ($list->length > 0) {
$title = $list->item(0)->textContent;
}
}
【讨论】:
抑制因不正确的 HTML 或缺少元素而导致的任何解析错误:
<?
$doc = new DOMDocument();
@$doc->loadHTML(@file_get_contents("http://www.washingtonpost.com"));
// find the title
$titlelist = $doc->getElementsByTagName("title");
if($titlelist->length > 0){
echo $titlelist->item(0)->nodeValue;
}
【讨论】:
loadHTMLFile 已经合并了 file_get_contents 并且不会在格式错误的 HTML 上给出错误,因此它产生的任何错误都是有价值的。 loadHTML 也不会在格式错误的 HTML 上给出错误。
$doc->loadHTMLFile("http://www.washingtonpost.com"); 时,我收到一堆错误,上面写着 Warning: DOMDocument::loadHTMLFile() [domdocument.loadhtmlfile]: htmlParseEntityRef: expecting ';'在washingtonpost.com 中,第 5 行的 /var/www/test/test2.php 中的第 52 行。也许是我的 PHP 版本,但是...
libxml_use_internal_errors(true);,这样你就可以在需要/需要时访问错误数据