php获取url标题

180it 2020-02-01 PM 922℃ 0条
/**
 * @title 获取url标题
 * @param $url @url链接
 * @return mixed|string
 */
function url_title($url)
{
    $ch = curl_init();
    curl_setopt_array($ch, array(
        CURLOPT_HEADER => false,
        CURLOPT_URL => $url,
        //考虑到有些网站是301跳转的.
        CURLOPT_FOLLOWLOCATION => true,
        //连接的超时时间设置为5秒
        CURLOPT_CONNECTTIMEOUT => 5,
        //响应超时时间为5秒
        CURLOPT_TIMEOUT => 5,
        CURLOPT_VERBOSE => false,
        CURLOPT_AUTOREFERER => true,
        //接收所有的编码
        CURLOPT_ENCODING => '',
        //返回页面内容
        CURLOPT_RETURNTRANSFER => true,
    ));
    $response = curl_exec($ch);
//检测网页的编码,把非UTF-8编码的页面,统一转换为UTF-8处理.
    if ('UTF-8' !== ($encoding = mb_detect_encoding($response, array('UTF-8', 'CP936', 'ASCII')))) {
        $response = mb_convert_encoding($response, 'UTF-8', $encoding);
    }
//匹配一下title
    $title = '';
    if (preg_match('#<title>(.*)</title>#isU', $response, $match)) {
        $title = $match[1];
    }
    return $title;
}
支付宝打赏支付宝打赏 微信打赏微信打赏

如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!

标签: none

php获取url标题