Fastest way to retrieve a <title> in PHP

前端 未结 7 1863
既然无缘
既然无缘 2020-11-28 12:12

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

7条回答
  •  被撕碎了的回忆
    2020-11-28 12:36

    I like using SimpleXml with regex's, this is from a solution I use to grab multiple link headers from a page in an OpenID library I've created. I've adapted it to work with the title (even though there is usually only one).

    function getTitle($sFile)
    {
        $sData = file_get_contents($sFile);
    
        if(preg_match('/]*>.*<\/head>/is', $sData, $aHead))
        {   
            $sDataHtml = preg_replace('/<(.[^>]*)>/i', strtolower('<$1>'), $aHead[0]);
            $xTitle = simplexml_import_dom(DomDocument::LoadHtml($sDataHtml));
    
            return (string)$xTitle->head->title;
        }
        return null;
    }
    
    echo getTitle('http://stackoverflow.com/questions/399332/fastest-way-to-retrieve-a-title-in-php');
    

    Ironically this page has a "title tag" in the title tag which is what sometime causes problems with the pure regex solutions.

    This solution is not perfect as it lowercase's the tags which could cause a problem for the nested tag if formatting/case was important (such as XML), but there are ways that are a bit more involved around that problem.

提交回复
热议问题