使用 cURL 函数获取网页标题,提供更安全高效的方式替代 file_get_contents 函数。

function get_title($url) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $content = curl_exec($ch);
    curl_close($ch);
    
    preg_match('/<title>(.*)</title>/i', $content, $title);
    $title = str_replace(array('\r\n', '\r', '\n', ',', ' '), '', $title[1]);
    
    return $title;
}

$title = get_title($t_url);

代码解释:

  1. 创建 cURL 资源$ch = curl_init($url);
  2. 设置选项curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 将结果返回到字符串而不是直接输出。
  3. 执行请求$content = curl_exec($ch);
  4. 关闭连接curl_close($ch);
  5. 正则表达式匹配标题preg_match('/<title>(.*)</title>/i', $content, $title);
  6. 清理标题$title = str_replace(array('\r\n', '\r', '\n', ',', ' '), '', $title[1]);
  7. 返回标题return $title;

优点:

  • 更安全:cURL 函数支持 HTTPS 连接,更安全。
  • 更灵活:cURL 函数允许设置更多选项,例如代理服务器、超时时间等。
  • 更高效:cURL 函数可以更好地处理网络错误,提高代码稳定性。

使用示例:

$t_url = 'https://www.example.com';
$title = get_title($t_url);

echo $title; // 输出网页标题
PHP 获取网页标题 - 使用 cURL 函数

原文地址: https://www.cveoy.top/t/topic/o7RN 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录