// 优先使用 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 语句处理异常。

使用方法:

  1. 将代码保存为 .php 文件
  2. $t_url 变量替换为要获取标题的网站 URL
  3. 运行代码,输出结果将是网站标题

代码说明:

  • 首先使用 file_get_contents 函数获取网站内容
  • 如果 file_get_contents 函数获取失败,则使用 curl 函数获取网站内容
  • 使用 preg_match 函数匹配网站标题标签 title
  • 使用 str_replace 函数去除标题中不需要的字符
  • 最后输出网站标题

代码优缺点:

优点:

  • 代码简洁易懂,易于维护
  • 使用 try-catch 语句处理异常,提高代码健壮性
  • 优先使用 file_get_contents 函数,性能更优

缺点:

  • 依赖于网络环境,如果网络连接不稳定,可能会导致代码执行失败
  • 无法获取所有网站的标题,因为某些网站可能会屏蔽 file_get_contentscurl 函数

其他:

  • file_get_contents 函数是 PHP 中常用的获取网页内容的函数,性能比 curl 函数更高
  • curl 函数是一个强大的网络通信库,可以用于发送各种类型的 HTTP 请求
  • 在实际应用中,可以使用其他方式获取网站标题,例如使用第三方 API 或 DOM 解析库
PHP 获取网站标题:优先使用 file_get_contents 或 curl

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

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