PHP 获取网页标题代码解析及优化
这段代码是一个获取网页标题的功能实现代码。它首先尝试使用'file_get_contents'函数获取网页内容,如果该函数返回false,则抛出一个异常。接着使用'curl'函数获取网页内容,并使用正则表达式匹配出网页标题。如果标题为空,则再次尝试使用'curl'函数获取网页内容并匹配标题,如果仍然为空,则使用'file_get_contents'函数获取网页内容并匹配标题。最终,将匹配到的标题去除换行符、逗号和空格,赋值给变量'$title'。
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]);
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]);
}
}
该代码使用了异常处理机制,增强了代码的健壮性,并提供了两种获取网页内容的方式,以确保能够获取到网页标题。此外,代码还使用正则表达式匹配网页标题,并对标题进行了清理,提高了代码的可读性和易用性。
原文地址: https://www.cveoy.top/t/topic/o7Ro 著作权归作者所有。请勿转载和采集!