PHP 获取网站标题:优先使用 file_get_contents 或 curl
// 优先使用 file_get_contents 函数获取网站内容
try {
$contents = file_get_contents($t_url);
if ($contents === false) {
throw new Exception('file_get_contents failed');
}
} catch (Exception $e) {
// 使用curl函数获取网页内容
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $t_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$contents = curl_exec($ch);
curl_close($ch);
}
preg_match('/<title>(.*)</title>/i', $contents, $title);
$title = str_replace(array("\r\n", "\r", "\n", ',', ' '), '', $title[1]);
// 如果使用 file_get_contents 获取不到标题,则使用 curl 函数获取
if (empty($title)) {
try {
// 使用curl函数获取网页内容
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $t_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$contents = curl_exec($ch);
curl_close($ch);
preg_match('/<title>(.*)</title>/i', $contents, $title);
$title = str_replace(array("\r\n", "\r", "\n", ',', ' '), '', $title[1]);
} catch (Exception $e) {
// 使用file_get_contents函数获取网页内容
$contents = file_get_contents($t_url);
preg_match('/<title>(.*)</title>/i', $contents, $title);
$title = str_replace(array("\r\n", "\r", "\n", ',', ' '), '', $title[1]);
}
}
本代码示例展示了如何使用 PHP 获取网站标题,优先使用 file_get_contents 函数,如果失败则使用 curl 函数。代码提供了两种方法,并通过 try-catch 语句处理异常。
使用方法:
- 将代码保存为
.php文件 - 将
$t_url变量替换为要获取标题的网站 URL - 运行代码,输出结果将是网站标题
代码说明:
- 首先使用
file_get_contents函数获取网站内容 - 如果
file_get_contents函数获取失败,则使用curl函数获取网站内容 - 使用
preg_match函数匹配网站标题标签title - 使用
str_replace函数去除标题中不需要的字符 - 最后输出网站标题
代码优缺点:
优点:
- 代码简洁易懂,易于维护
- 使用
try-catch语句处理异常,提高代码健壮性 - 优先使用
file_get_contents函数,性能更优
缺点:
- 依赖于网络环境,如果网络连接不稳定,可能会导致代码执行失败
- 无法获取所有网站的标题,因为某些网站可能会屏蔽
file_get_contents或curl函数
其他:
file_get_contents函数是 PHP 中常用的获取网页内容的函数,性能比curl函数更高curl函数是一个强大的网络通信库,可以用于发送各种类型的 HTTP 请求- 在实际应用中,可以使用其他方式获取网站标题,例如使用第三方 API 或 DOM 解析库
原文地址: https://www.cveoy.top/t/topic/o7Rl 著作权归作者所有。请勿转载和采集!