Fastest way to retrieve a <title> in PHP

前端 未结 7 1829
既然无缘
既然无缘 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:40
    <?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.

    0 讨论(0)
提交回复
热议问题