」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > CURL 可以取代 file_get_contents 來取得外部連結嗎?

CURL 可以取代 file_get_contents 來取得外部連結嗎?

發佈於2024-11-16
瀏覽:578

Can CURL Be an Alternative to file_get_contents for Fetching External Links?

使用 CURL 獲取外部鏈接(替代 file_get_contents)

為了獲取特定頁面上的外部鏈接,通常使用 file_get_contents 函數。但是,當您使用的伺服器不支援此功能時,CURL 可以作為可行的替代方案。

要實作 CURL,您可以使用以下程式碼:

function file_get_contents_curl($url) {
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);

    $data = curl_exec($ch);
    curl_close($ch);

    return $data;
}

// Usage Example
echo file_get_contents_curl('http://google.com');

但如果此程式碼傳回空白頁面,則可能需要啟用 URL 重新導向。若要解決此問題,請以下列方式修改程式碼:

function file_get_contents_curl($url) {
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);       

    $data = curl_exec($ch);
    curl_close($ch);

    return $data;
}
版本聲明 本文轉載於:1729171883如有侵犯,請洽[email protected]刪除
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3