在PHP中检索<title>的最快方法

21 html php parsing

我正在做一个书签系统,并寻找用PHP检索页面标题的最快(最简单)方法.

有类似的东西会很高兴 $title = page_title($url)

Ed *_*rel 47

<?php
    function page_title($url) {
        $fp = file_get_contents($url);
        if (!$fp) 
            return null;

        $res = preg_match("/<title>(.*)<\/title>/siU", $fp, $title_matches);
        if (!$res) 
            return null; 

        // Clean up title: remove EOL's and excessive whitespace.
        $title = preg_replace('/\s+/', ' ', $title_matches[1]);
        $title = trim($title);
        return $title;
    }
?>
Run Code Online (Sandbox Code Playgroud)

给出了以下输入的动力:

print page_title("http://www.google.com/");
Run Code Online (Sandbox Code Playgroud)

输出:谷歌

希望一般足以满足您的使用需求.如果您需要更强大的功能,那么花一点时间研究HTML解析器可能不会有什么坏处.

编辑:添加了一些错误检查.有点冲出第一个版本,对不起.

  • Facebook的标题标签如下所示:`<title id ="pageTitle">` (4认同)

Luk*_*kas 15

没有reg表达式你可以得到它:

$title = '';
$dom = new DOMDocument();

if($dom->loadHTMLFile($urlpage)) {
    $list = $dom->getElementsByTagName("title");
    if ($list->length > 0) {
        $title = $list->item(0)->textContent;
    }
}
Run Code Online (Sandbox Code Playgroud)


Ale*_*ski 9

或者使这个简单的功能稍微更具防弹性:

function page_title($url) {

    $page = file_get_contents($url);

    if (!$page) return null;

    $matches = array();

    if (preg_match('/<title>(.*?)<\/title>/', $page, $matches)) {
        return $matches[1];
    } else {
        return null;
    }
}


echo page_title('http://google.com');
Run Code Online (Sandbox Code Playgroud)


wil*_*lks 7

我也在做一个书签系统,发现从 PHP 5 开始,你可以用来stream_get_line加载远程页面,直到结束标题标签(而不是加载整个文件),然后去掉开始标题标签之前的内容explode(而不是加载整个文件)正则表达式)。

function page_title($url) {
  $title = false;
  if ($handle = fopen($url, "r"))  {
    $string = stream_get_line($handle, 0, "</title>");
    fclose($handle);
    $string = (explode("<title", $string))[1];
    if (!empty($string)) {
      $title = trim((explode(">", $string))[1]);
    }
  }
  return $title;
}
Run Code Online (Sandbox Code Playgroud)

最后explode感谢 PlugTrade 的回答,他提醒我标题标签可以有属性。


ale*_*lex 5

正则表达式?

使用cURL获取$ htmlSource变量的内容.

preg_match('/<title>(.*)<\/title>/iU', $htmlSource, $titleMatches);

print_r($titleMatches);
Run Code Online (Sandbox Code Playgroud)

看看你在那个数组中有什么.

大多数人说HTML遍历虽然你应该使用解析器,因为正则表达式可能不可靠.

其他答案提供更多细节:)