doulue7522 2011-04-27 22:32
浏览 81
已采纳

使用来自localhost的curl

I'm just trying to fetch the yahoo web page. www.yahoo.com

If I run my simple script from my hosted site, it works.

If I try it from my localhost. All I get is a header response with: "w32.fp.re1.yahoo.com uncompressed/chunked Wed Apr 27 15:13:48 PDT 2011"

Here is my code:

    <?php

function curl_download($Url){

    // is cURL installed yet?
    if (!function_exists('curl_init')){
        die('Sorry cURL is not installed!');
    }


    // OK cool - then let's create a new cURL resource handle
    $ch = curl_init();

    // Now set some options (most are optional)

    // Set URL to download
    curl_setopt($ch, CURLOPT_URL, $Url);

    // Set a referer
    curl_setopt($ch, CURLOPT_REFERER, "http://www.example.org/yay.htm");

    // User agent
    curl_setopt($ch, CURLOPT_USERAGENT, "MozillaXYZ/1.0");

    // Include header in result? (0 = yes, 1 = no)
    curl_setopt($ch, CURLOPT_HEADER, 0);

    // Should cURL return or print out the data? (true = return, false = print)
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    // Timeout in seconds
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);

    // Download the given URL, and return output
    $output = curl_exec($ch);

    // Close the cURL resource, and free system resources
    curl_close($ch);

    return $output;
}


print curl_download('http://www.yahoo.com/');
?>
  • 写回答

1条回答 默认 最新

  • douzhang7728 2011-04-28 00:11
    关注

    Actually, the result starts with

    HTTP/1.1 302 Found
    

    which means there's a Location header in there. And there is:

    Location: http://nl.yahoo.com/?p=us
    

    This is just the response body:

    <!-- w20.fp.ird.yahoo.com uncompressed/chunked Wed Apr 27 17:08:09 PDT 2011 -->
    

    You need to tell cURL to follow Location headers. That's it.

    The name of the option is CURLOPT_FOLLOWLOCATION. Set it to true:

    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    

    PS
    After following 1 Location header, this is the start of the response body when I run your code + FOLLOWLOCATION:

    <!DOCTYPE html>
    <html lang="nl-NL" class="y-fp-bg y-fp-pg-grad  bkt732">
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog