使用cURL和file_get_contents并发获取网站标题

本文介绍使用PHP的cURL和file_get_contents函数并发获取网站标题的方法,并提供示例代码。通过比较获取速度来选择最佳方案,提升网站标题获取效率。

示例代码:

<?php
function getWebsiteTitle($url) {
    $title = '';

    // 创建一个cURL句柄
    $ch = curl_init();

    // 设置cURL选项
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);

    // 执行cURL请求
    $curlResult = curl_exec($ch);

    // 检查cURL请求是否成功
    if ($curlResult !== false) {
        // 使用正则表达式提取标题
        preg_match('/<title>(.*)</title>/i', $curlResult, $matches);
        $title = str_replace(array('\r\n', '\r', '\n', ',', ' '), '', $matches[1]);

        // 如果file_get_contents请求仍在运行,则停止
        if (function_exists('curl_multi_select')) {
            $running = null;
            do {
                curl_multi_exec($ch, $running);
                curl_multi_select($ch);
            } while ($running > 0);
        }

        // 关闭cURL句柄
        curl_close($ch);
    }

    // 如果cURL请求不成功或未找到标题,则回退到使用file_get_contents
    if (empty($title)) {
        $contents = file_get_contents($url);
        preg_match('/<title>(.*)</title>/i', $contents, $matches);
        $title = str_replace(array('\r\n', '\r', '\n', ',', ' '), '', $matches[1]);
    }

    return $title;
}

// 示例使用
$t_url = 'https://example.com'; // 替换为您的目标URL
$title = getWebsiteTitle($t_url);
echo $title;
?>

代码说明:

  1. 创建一个cURL句柄并设置选项,例如URL、返回结果、头部信息等。
  2. 执行cURL请求并检查是否成功。
  3. 使用正则表达式提取标题。
  4. 使用curl_multi_selectcurl_multi_exec函数判断file_get_contents请求是否仍在运行,如果仍在运行,则停止执行。
  5. 关闭cURL句柄。
  6. 如果cURL请求失败或未找到标题,则回退到使用file_get_contents获取标题。

优势:

通过使用并发方式获取网站标题,可以有效提升网站标题获取效率。如果cURL请求更快,则可以提前获取到标题,并停止file_get_contents请求的执行,从而减少不必要的等待时间。

注意:

  • curl_multi_selectcurl_multi_exec函数需要PHP版本大于等于5.5才能使用。
  • 为了确保并发执行的可靠性,建议设置合理的连接超时时间。
  • 应根据实际情况选择合适的获取方式,并进行必要的优化,以获得最佳的性能。
PHP并发获取网站标题 - 使用cURL和file_get_contents提升效率

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

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