栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何从php脚本创建和下载csv文件?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何从php脚本创建和下载csv文件?

您可以为数组使用内置的fputcsv()从数组中生成正确的csv行,因此您必须循环并收集行。喜欢:

$f = fopen("tmp.csv", "w");foreach ($array as $line) {    fputcsv($f, $line)}

为了使浏览器提供“另存为”对话框,您必须像这样发送HTTP标头:

header('Content-Disposition: attachment; filename="filename.csv";');

放在一起:

function array_to_csv_download($array, $filename = "export.csv", $delimiter=";") {    // open raw memory as file so no temp files needed, you might run out of memory though    $f = fopen('php://memory', 'w');     // loop over the input array    foreach ($array as $line) {         // generate csv lines from the inner arrays        fputcsv($f, $line, $delimiter);     }    // reset the file pointer to the start of the file    fseek($f, 0);    // tell the browser it's going to be a csv file    header('Content-Type: application/csv');    // tell the browser we want to save it instead of displaying it    header('Content-Disposition: attachment; filename="'.$filename.'";');    // make php send the generated csv lines to the browser    fpassthru($f);}

您可以像这样使用它:

array_to_csv_download(array(  array(1,2,3,4), // this array is going to be the first row  array(1,2,3,4)), // this array is going to be the second row  "numbers.csv");

更新:
除了,

php://memory
您还可以将
php://output
用作文件描述符,并取消查找等:

function array_to_csv_download($array, $filename = "export.csv", $delimiter=";") {    header('Content-Type: application/csv');    header('Content-Disposition: attachment; filename="'.$filename.'";');    // open the "output" stream    // see http://www.php.net/manual/en/wrappers.php.php#refsect2-wrappers.php-unknown-unknown-unknown-descriptioq    $f = fopen('php://output', 'w');    foreach ($array as $line) {        fputcsv($f, $line, $delimiter);    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/465810.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号