问题描述
是否可以进行卷曲,访问url并将结果作为文件资源?
Is it possible to make curl, access a url and the result as a file resource? like how fopen does it.
我的目标:
- 解析CSV文件
- 将其传递给fgetcsv
我的障碍:fopen被禁用
My obstruction: fopen is disabled
我的代码块(在fopen中)
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);
但是,像往常一样。 $ content已经返回一个字符串。
But, as usual. $content already returns a string.
现在,curl是否有可能将其作为文件资源指针返回?就像fopen一样?使用PHP< 5.1.x的东西。我的意思是,不使用str_getcsv,因为它只有5.3。
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.
我的错误
谢谢
推荐答案
假定通过 fopen禁用了
,您的意思是 allow_url_fopen
已禁用,将 CURLOPT_FILE
和使其变得相当简单:
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);
基本上,这会创建一个指向虚拟文件的指针,并且cURL将响应存储在其中。然后,只需将指针重置为开始,就可以像使用 fopen($ url,'r');
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');
这篇关于使用curl作为fgetcsv的fopen文件资源的替代方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!