Fastest way to retrieve a <title> in PHP

前端 未结 7 1860
既然无缘
既然无缘 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:32

    I'm also doing a bookmarking system and found that since PHP 5 you can use stream_get_line to load the remote page only until the closing title tag (instead of loading the whole file), then get rid of what's before the opening title tag with explode (instead of a regex).

    function page_title($url) {
      $title = false;
      if ($handle = fopen($url, "r"))  {
        $string = stream_get_line($handle, 0, "");
        fclose($handle);
        $string = (explode("", $string))[1]);
        }
      }
      return $title;
    }
    

    Last explode thanks to PlugTrade's answer who reminded me that title tags can have attributes.

提交回复
热议问题