Grabbing CSV over cURL in PHP

我只是一个虾纸丫 提交于 2019-12-19 12:01:08

问题


Unfortunately, I cannot use either fopen or file_get_contents, so my working script has become a broken one using cURL:

$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$tmp = curl_exec($ch);
curl_close($ch);
header("Content-type: application/csv");
header(Content-Disposition: attachment; filename=$start.csv");
header("Pragma: no-cache");
header("Expires: 0");
echo $tmp;

URL going in is a CSV file - and the fopen version of this worked before. All I get is an empty CSV file returned to the browser.

Thanks.


回答1:


Ok there could be a couple of places which went wrong, most likely the $tmp variable will be your key.

I am assuming the $url and $start variables have been declared correctly

First thing I would suggest is to do something along the lines of:

    if( ! $tmp = curl_exec($ch))
        {
           echo curl_error($ch);
        } 

    else
    {

        header("Content-type: application/csv");
        header("Content-Disposition: attachment; filename=$start.csv");
        header("Pragma: no-cache");
        header("Expires: 0");
        echo $tmp;
    }
    curl_close($ch);

Might give you an idea about what is going wrong




回答2:


By default curl_exec returns a boolean. You need to set the CURLOPT_RETURNTRANSFER option to 1 or true to get the transfer payload returned.




回答3:


Set CURLOPT_RETURNTRANSFER to 1 so you get something into $tmp, otherwise curl_exec outputs the csv directly (and before you send the headers). See http://www.php.net/manual/en/function.curl-setopt.php




回答4:


I believe that curl_exec($ch) will not return a string unless you use curl_setopt($ch,CURLOPT_RETURNTRANSFER,true) first.



来源:https://stackoverflow.com/questions/7160793/grabbing-csv-over-curl-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!