Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using curl as an alternative to fopen file resource for fgetcsv

Is it possible to make curl, access a url and the result as a file resource? like how fopen does it.

My goals:

  1. Parse a CSV file
  2. Pass it to fgetcsv

My obstruction: fopen is disabled

My chunk of codes (in fopen)

$url = "http://download.finance.yahoo.com/d/quotes.csv?s=USDEUR=X&f=sl1d1t1n&e=.csv";
$f = fopen($url, 'r');
print_r(fgetcsv($f));

Then, I am trying this on curl.

$curl = curl_init();
curl_setopt($curl, CURLOPT_VERBOSE, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, false);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $param);
curl_setopt($curl, CURLOPT_URL, $url);
$content = @curl_exec($curl);
curl_close($curl);

But, as usual. $content already returns a string.

Now, is it possible for curl to return it as a file resource pointer? just like fopen? Using PHP < 5.1.x something. I mean, not using str_getcsv, since it's only 5.3.

My error

Warning: fgetcsv() expects parameter 1 to be resource, boolean given

Thanks

like image 473
Louie Miranda Avatar asked Aug 08 '12 15:08

Louie Miranda


1 Answers

Assuming that by fopen is disabled you mean "allow_url_fopen is disabled", a combination of CURLOPT_FILE and php://temp make this fairly easy:

$f = fopen('php://temp', 'w+');

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_FILE, $f);
// Do you need these? Your fopen() method isn't a post request
// curl_setopt($curl, CURLOPT_POST, true);
// curl_setopt($curl, CURLOPT_POSTFIELDS, $param);
curl_exec($curl);
curl_close($curl);

rewind($f);

while ($line = fgetcsv($f)) {
  print_r($line);
}

fclose($f);

Basically this creates a pointer to a "virtual" file, and cURL stores the response in it. Then you just reset the pointer to the beginning and it can be treated as if you had opened it as usual with fopen($url, 'r');

like image 190
DaveRandom Avatar answered Oct 23 '22 05:10

DaveRandom