嘗試使用cURL 抓取網頁的HTML 內容時cURL,會遇到重定向或“頁面移動”錯誤。這通常可以歸因於查詢字串中特殊編碼的字元。
要有效檢索頁面內容而不遇到這些問題,請如下優化cURL 程式碼:
<code class="php">function get_web_page($url) { $user_agent='Mozilla/5.0 (Windows NT 6.1; rv:8.0) Gecko/20100101 Firefox/8.0'; $options = array( CURLOPT_CUSTOMREQUEST => "GET", CURLOPT_POST => false, CURLOPT_USERAGENT => $user_agent, CURLOPT_COOKIEFILE => "cookie.txt", CURLOPT_COOKIEJAR => "cookie.txt", CURLOPT_RETURNTRANSFER => true, CURLOPT_HEADER => false, CURLOPT_FOLLOWLOCATION => true, CURLOPT_ENCODING => "", CURLOPT_AUTOREFERER => true, CURLOPT_CONNECTTIMEOUT => 120, CURLOPT_TIMEOUT => 120, CURLOPT_MAXREDIRS => 10, ); $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; }</code>
<code class="php">$result = get_web_page($url); if ($result['errno'] != 0) // Error handling for invalid URL, timeout, or redirect loops. if ($result['http_code'] != 200) // Error handling for issues like missing page, permission denial, or unavailability. $page = $result['content'];</code>
以上是如何使用錯誤處理的 cURL 高效提取頁面內容?的詳細內容。更多資訊請關注PHP中文網其他相關文章!