通过链接获取网站标题 [英] Get title of website via link

查看:32
本文介绍了通过链接获取网站标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请注意 Google 新闻如何在每篇文章摘录的底部提供来源.

Notice how Google News has sources on the bottom of each article excerpt.

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

The Guardian - ABC News - Reuters - Bloomberg

我正在尝试模仿.

例如,在提交 URL http://www.washingtontimes.com/news/2010/dec/3/debt-panel-fails-test-vote/ 我想返回 <代码>华盛顿时报

For example, upon submitting the URL http://www.washingtontimes.com/news/2010/dec/3/debt-panel-fails-test-vote/ I want to return The Washington Times

用 php 怎么可能?

How is this possible with php?

推荐答案

我的回答是对@AI W 使用页面标题的回答进行了扩展.下面是实现他所说的代码.

My answer is expanding on @AI W's answer of using the title of the page. Below is the code to accomplish what he said.

<?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/");

?>

输出

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

Washington Times - Politics, Breaking News, US and World News

正如您所看到的,这并不是 Google 正在使用的,所以这让我相信他们获取了 URL 的主机名并将其与自己的列表匹配.

As you can see, it is not exactly what Google is using, so this leads me to believe that they get a URL's hostname and match it to their own list.

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

这篇关于通过链接获取网站标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆