php - PHP数组到CSV输出整个html页面
问题描述
我正在尝试使用以下代码使用 PHP 将数组输出到 CSV。但是,它将整个 HTML 页面输出到 CSV。我该如何编写它,以便它只将数组输出到 CSV 而不是页面的代码?
我认为问题与以下有关:
$f = fopen('php://output', 'w');
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://output', '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($data_array);
解决方案
您在标题之前发送输出。
您可以简化为:
<?php
function array_to_csv_download($array, $filename = "export.csv", $delimiter=";") {
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="'.$filename.'";');
$f = fopen('php://output', 'w');
foreach ($array as $line)
fputcsv($f, $line, $delimiter);
}
确保在这些标头调用之前不输出任何其他内容。
推荐阅读
- firebase - 如何制定安全的 Cloud Firestore 安全规则
- asynchronous - 使用异步 Rust 时如何修复“ld:无法写入输出文件”错误?
- php - 使用 Join CodeIgniter 制作动态模型
- google-sheets - 查询函数在 Col19 之后不拉数据
- python - 无法在我的自定义数据集中训练更快的 rcnn 模型
- c++ - 具有两个未知数的线性方程的调试代码
- php - 延迟显示页面中的单个项目
- javascript - Angular - async/await Observable toPromise 更新广播新的 BehaviorSubject 数据返回 Promise
- python - 在单个图中绘制多个饼图
- node.js - 数组 .split() 方法在 Heroku 应用程序中无法正常工作