File download for csv works in local host but not when live

两盒软妹~` 提交于 2019-12-25 11:25:24

问题


I am creating a csv file from nested array and it works fine with a download link to the csv file in the localhost, but on live host it won't download. This is what is in my php file:

The headers declared:

/**
* Declare headers for CSV
 */
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=registration.csv");
header("Pragma: no-cache");
header("Expires: 0");

The Function that outputs the csv file:

/**
* Function will output the scsv file
* @param the csv $data in nested array form array(array("","",""),array("",""...)...)
*/
function outputCSV($data) {
$outstream = fopen("php://output", "w");
function __outputCSV(&$vals, $key, $filehandler) {
    fputcsv($filehandler, $vals); // add parameters if you want
}
array_walk($data, "__outputCSV", $outstream);
fclose($outstream);
}

The link that I used in local:

<a href=".../csv/csv.php">Download CSV</a>

Won't work on Live site. Instead of downloading it just takes me to the csv.php page and outputs the array in a string like this.

...ID,"Coach One","Coach Two",Work,Cell,Email,...


回答1:


Try hardcoding the csv into the code. Replace these lines with the ones you have to see if your data being passed has bad characters. Maybe specifying the charset will help.

header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
$output = fopen('php://output', 'w');
fputcsv($output, array('Column 1', 'Column 2', 'Column 3'));

As described here:

http://code.stephenmorley.org/php/creating-downloadable-csv-files/




回答2:


I'm not setup to really debug your code. You can try this though if you like. I know it works.

$out = fopen("php://temp", 'r+');
while (($row = $res->fetch(Zend_Db::FETCH_NUM)) != false) {
    fputcsv($out, $row, ',', '"');
}                       
rewind($out);
$csv  = stream_get_contents($out);
header("Content-Type: application/csv;");
header("Content-Disposition: attachment; filename=\"foo.csv\"");        
header("Pragma: no-cache");
header("Expires: 0");        
echo $csv;
exit(0); 

Adjust the loop as needed to iterate on your results.



来源:https://stackoverflow.com/questions/13977022/file-download-for-csv-works-in-local-host-but-not-when-live

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