首頁  >  文章  >  後端開發  >  CURL 可以取代 file_get_contents 來取得外部連結嗎?

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

Susan Sarandon
Susan Sarandon原創
2024-10-17 21:34:30716瀏覽

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;
}

以上是CURL 可以取代 file_get_contents 來取得外部連結嗎?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn