使用 PHP 获取网站标题:file_get_contents 和 curl

获取网站标题是网页爬虫中常见的操作,可以使用 file_get_contents 函数来获取网页内容,并使用正则表达式提取标题。然而,file_get_contents 函数有时会失败,例如目标网站无法访问或服务器响应过慢。为了确保代码的稳定性,我们可以使用 curl 函数作为备选方案。

以下代码示例展示了使用 file_get_contentscurl 获取网站标题的步骤,并使用 try-catch 语句处理 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('
', '
', '
', ',', ' '), '', $title[1]);

在上面的代码中,我们使用 try-catch 语句来捕获 file_get_contents 函数可能抛出的异常。如果 file_get_contents 函数失败,则使用 curl 函数获取网页内容。然后,使用 preg_matchstr_replace 函数获取和处理网站标题。

注意:

  • 代码中的 $t_url 变量需要替换为目标网站的 URL 地址。
  • 为了防止爬虫行为被网站屏蔽,建议在请求网站时设置合理的请求头信息,例如 User-Agent
PHP 获取网站标题:使用 file_get_contents 和 curl 两种方法

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

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