在PHP中为用户创建CSV文件 [英] Create a CSV File for a user in PHP

查看:149
本文介绍了在PHP中为用户创建CSV文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个MySQL数据库中的数据。我向用户发送一个URL,以便将其数据作为CSV文件发布。



我有电子邮件的链接,MySQL查询等。 / p>

我如何在点击链接时弹出下载一个带有MySQL记录的CVS?



我有所有的信息来获取记录。我只是不知道如何让PHP创建CSV文件,并让他们下载一个.CSV扩展名的文件。

解决方案

尝试:

  header(Content-type:text / csv); 
header(Content-Disposition:attachment; filename = file.csv);
header(Pragma:no-cache);
header(Expires:0);

echorecord1,record2,record3 \\\
;



编辑:的代码用于可选地编码CSV字段:

 函数maybeEncodeCSVField($ string){
if(strpos string,',')!== false || strpos($ string,'')!== false || strpos($ string,\\\
)!== false){
$ string =''。 str_replace('','',$ string)。'';
}
return $ string;
}


I have data in a MySQL database. I am sending the user a URL to get their data out as a CSV file.

I have the e-mailing of the link, MySQL query, etc. covered.

How can I, when they click the link, have a pop-up to download a CVS with the record from MySQL?

I have all the information to get the record already. I just don't see how to have PHP create the CSV file and let them download a file with a .csv extension.

解决方案

Try:

header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");

echo "record1,record2,record3\n";

etc

Edit: Here's a snippet of code I use to optionally encode CSV fields:

function maybeEncodeCSVField($string) {
    if(strpos($string, ',') !== false || strpos($string, '"') !== false || strpos($string, "\n") !== false) {
        $string = '"' . str_replace('"', '""', $string) . '"';
    }
    return $string;
}

这篇关于在PHP中为用户创建CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆