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

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

问题描述

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



如果有 $ title = page_title($ url)

解决方案

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

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

//清理标题:删除EOL和过多的空白。
$ title = preg_replace('/ \s + /','',$ title_matches [1]);
$ title = trim($ title);
返回$ title;
}
?>

给以下输入提供了一个旋钮:

 打印page_title(http://www.google.com/);  

$ b

输出:Google

为您的使用。如果你需要更强大的功能,花一点时间研究HTML解析器可能没有什么意义。



编辑:添加了一些错误检查。种类冲第一个版本,对不起。

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

It would be nice to have something like $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;
    }
?>

Gave 'er a whirl on the following input:

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

Outputted: Google

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.

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

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

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