开发者

How to use PHP to send a CSV file to a user through an AJAX call?

I have a PHP file dataAPI.php which returns an array of data that is either serialized as JSON or (as I'm trying to implement) CSV. dataAPI.php is accessed exclusively through AJAX calls, which has worked fine so far with JSON data.

The problem is, I want to also have an export button on the client-side, which when clicked, would send another AJAX call to return the same data s开发者_如何转开发erialized in the CSV format. I know I can't send files over AJAX, so how would I go about doing this?

I've thought of creating CSV files on the server side, and then sending a redirect-url as the response to my AJAX request. If I did this though, how could I prevent two requests overwriting each others files and remove already accessed/old csv files? Is there a better way? Any help is appreciated.


You could try returning JSON in either case, except that the CSV version would return a JSON object that has one value - a long string containing the CSV data.


1) For the AJAX call, create the file somewhere on the server and send a link back - this link can then be either redirected to (e.g. in a subwindow), or clicked on...

2) To prevent data being overwritten by different requests, create an unique filename server-side (e.g. with the uniq_id() function). You can still send them with the same filename with a header() tag. Make sure you delete those files once you are sure you no longer need them (I personally use a housekeeping script like the following:

$timeout = 43200; // Max age in seconds
$cleanPaths = array("ps_files/"); // The directory to autoclean

foreach ($cleanPaths as $URLPath) {
    if ($handle = opendir($URLPath)) {
        while (false !== ($file = readdir($handle))) {
            if ((substr($file, 0, 1) !== ".") && ((time() - filectime($URLPath . $file)) >= $timeout)) {
                unlink($URLPath . $file);
            }
        }
    }
}


You can put the following code in a file and then send an xhr request to it invoking the file. Or you can try opening the file in a separate tool less pop up.

$result = mysql_query("SHOW COLUMNS FROM `$table`");
$i = 0;
if (mysql_num_rows($result) > 0) {
    while ($row = mysql_fetch_assoc($result)) {
       $csv_output .= $row['Field'].", ";
       $i++;
    }
}
$csv_output .= "\n";

$values = mysql_query("SELECT * FROM `$table`");
while ($rowr = mysql_fetch_row($values)) {
    for ($j=0;$j<$i;$j++) {
        $csv_output .= $rowr[$j].", ";
    }
    $csv_output .= "\n";
}

$filename = $file."_".date("Y-m-d_H-i",time());
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
print $csv_output;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜