PHP 获取网页标题 - 使用 cURL 函数
使用 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);
代码解释:
- 创建 cURL 资源:
$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;
优点:
- 更安全:cURL 函数支持 HTTPS 连接,更安全。
- 更灵活:cURL 函数允许设置更多选项,例如代理服务器、超时时间等。
- 更高效:cURL 函数可以更好地处理网络错误,提高代码稳定性。
使用示例:
$t_url = 'https://www.example.com';
$title = get_title($t_url);
echo $title; // 输出网页标题
原文地址: https://www.cveoy.top/t/topic/o7RN 著作权归作者所有。请勿转载和采集!