lodhb lodhb - 1 year ago 84
PHP Question

fopen() fails sporadically

I know fopen() failures have been discussed profusely here, but it seems my problem has a unique twist to it: fopen() fails maybe one out of four times, the other times it works perfectly. I get the following error:

Warning: fopen(http://download.finance.yahoo.com/d/quotes.csv?s=0005.HK&f=nl1c1p2v&e=.csv)
[function.fopen]: failed to open stream: HTTP request failed! in [...] on line 4

The fact that it doesn't happen systematically rules out most problem sources on the host server side, could it be due to the server from which I'm fopening, Yahoo Finance?

Answer Source

Use curl lib instead. http://php.net/manual/en/book.curl.php

function get_cURL($p_url)

    $ch = curl_init($p_url);

    $agent = "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv: Gecko/2008092417 Firefox/3.0.3";
    $header[0] = "Accept: text/xml,text/csv,application/xhtml+xml,"; 
    $header[0] .= "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"; 
    $header[] = "Cache-Control: max-age=0"; 
    $header[] = "Connection: keep-alive"; 
    $header[] = "Keep-Alive: 300"; 

    // set URL and other appropriate options
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header); 
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
    // grab URL and pass it to the browser
    curl_setopt($ch, CURLOPT_URL, $p_url);
    curl_setopt($ch, CURLOPT_USERAGENT, $agent); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);

    $buffer = curl_exec($ch);
    $this->info = curl_getinfo($ch);
    $this->error = curl_error($ch);


return $buffer;