嘗試使用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中文網其他相關文章!