CURL は外部リンクを取得するための file_get_contents の代替になり得ますか?

Susan Sarandon
リリース: 2024-10-17 21:34:30
オリジナル
716 人が閲覧しました

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

Using CURL to Fetch External Links (Alternative to file_get_contents)

For fetching external links on a specific page, the file_get_contents function is typically employed. However, when the server you're using doesn't support this function, CURL can serve as a viable alternative.

To implement CURL, you can utilize the following code:

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');
ログイン後にコピー

But in cases where this code returns a blank page, it's likely that enabling URL redirection is necessary. To address this issue, modify the code in the following manner:

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 中国語 Web サイトの他の関連記事を参照してください。

ソース:php
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
著者別の最新記事
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!