检索 <title> 的最快方法在 PHP 中 [英] Fastest way to retrieve a <title> in PHP

查看:38
本文介绍了检索 <title> 的最快方法在 PHP 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm doing a bookmarking system and looking for the fastest (easiest) way to retrieve a page's title with PHP.

如果有像 $title = page_title($url)

推荐答案

<?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;
    }
?>

对以下输入试一试:

print page_title("http://www.google.com/");

输出:谷歌

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

Hopefully general enough for your usage. If you need something more powerful, it might not hurt to invest a bit of time into researching HTML parsers.

添加了一些错误检查.有点匆忙推出第一个版本,抱歉.

Added a bit of error checking. Kind of rushed the first version out, sorry.

这篇关于检索 &lt;title&gt; 的最快方法在 PHP 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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