通过链接获取网站标题

2022-08-30 11:36:08

请注意 Google 新闻在每篇文章摘录的底部都有来源。

卫报 - ABC新闻 - 路透社 - 彭博社

我试图模仿它。

例如,在提交 URL 时,我想返回http://www.washingtontimes.com/news/2010/dec/3/debt-panel-fails-test-vote/The Washington Times

这怎么可能用 php 实现?


答案 1

我的答案是扩展@AI W的答案使用页面的标题。以下是完成他所说的代码。

<?php

function get_title($url){
  $str = file_get_contents($url);
  if(strlen($str)>0){
    $str = trim(preg_replace('/\s+/', ' ', $str)); // supports line breaks inside <title>
    preg_match("/\<title\>(.*)\<\/title\>/i",$str,$title); // ignore case
    return $title[1];
  }
}
//Example:
echo get_title("http://www.washingtontimes.com/");

?>

输出

华盛顿时报 - 政治,突发新闻,美国和世界新闻

如您所见,这并不完全是Google正在使用的,因此这使我相信他们获得了URL的主机名并将其与自己的列表相匹配。

http://www.washingtontimes.com/ => 华盛顿时报


答案 2
$doc = new DOMDocument();
@$doc->loadHTMLFile('http://www.washingtontimes.com/news/2010/dec/3/debt-panel-fails-test-vote/');
$xpath = new DOMXPath($doc);
echo $xpath->query('//title')->item(0)->nodeValue."\n";

输出:

债务委员会在测试投票中不足 - 华盛顿时报

显然,您还应该实现基本的错误处理。


推荐