首页  >  文章  >  后端开发  >  如何使用cURL有效检索页面内容?

如何使用cURL有效检索页面内容?

DDD
DDD原创
2024-10-22 20:54:29419浏览

How Can I Retrieve Page Content Effectively with cURL?

如何使用 cURL 检索页面内容

尝试使用 cURL 抓取页面内容时,您可能会遇到重定向问题或“页面已移动”错误,特别是如果查询字符串包含特殊字符。

要解决此问题,您需要确保正确处理编码的查询字符串。这是解决此问题的改进代码片段:

<code class="php">/**
 * Function to retrieve a web page using cURL.
 */
function get_web_page(string $url): array
{
    $user_agent = 'Mozilla/5.0 (Windows NT 6.1; rv:8.0) Gecko/20100101 Firefox/8.0';

    $options = [
        CURLOPT_CUSTOMREQUEST  => "GET",        // Set request type as GET
        CURLOPT_POST           => false,        // Set to GET
        CURLOPT_USERAGENT      => $user_agent, // Set user agent
        CURLOPT_COOKIEFILE     => "cookie.txt", // Set cookie file
        CURLOPT_COOKIEJAR      => "cookie.txt", // Set cookie jar
        CURLOPT_RETURNTRANSFER => true,     // Return web page
        CURLOPT_HEADER         => false,    // Don't return headers
        CURLOPT_FOLLOWLOCATION => true,     // Follow redirects
        CURLOPT_ENCODING       => "",       // Handle all encodings
        CURLOPT_AUTOREFERER    => true,     // Set referer on redirect
        CURLOPT_CONNECTTIMEOUT => 120,      // Timeout on connect
        CURLOPT_TIMEOUT        => 120,      // Timeout on response
        CURLOPT_MAXREDIRS      => 10,       // Stop after 10 redirects
    ];

    $ch = curl_init($url);
    curl_setopt_array($ch, $options);
    $content = curl_exec($ch);
    $err = curl_errno($ch);
    $errmsg = curl_error($ch);
    $header = curl_getinfo($ch);
    curl_close($ch);

    $header['errno'] = $err;
    $header['errmsg'] = $errmsg;
    $header['content'] = $content;
    return $header;
}

// Example of using the function to get a web page:
$result = get_web_page('https://www.example.com/page');

if ($result['errno'] != 0) {
    // Handle error: bad url, timeout, redirect loop
}

if ($result['http_code'] != 200) {
    // Handle error: no page, no permissions, no service
}

$page = $result['content'];</code>

通过包含这些附加选项,例如将请求类型设置为 GET、提供用户代理以及处理所有编码,您应该能够成功检索所需网页的内容。

以上是如何使用cURL有效检索页面内容?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn