首页  >  文章  >  后端开发  >  CURL 可以替代 file_get_contents 来获取外部链接吗?

CURL 可以替代 file_get_contents 来获取外部链接吗?

Susan Sarandon
Susan Sarandon原创
2024-10-17 21:34:30719浏览

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