【发布时间】:2015-07-01 05:02:52
【问题描述】:
我在我的插件页面中使用了一个简单的数组到 CSV 导出功能来生成报告。
当我运行此代码时,我收到一个错误,它将导出整个 html 内容以及我预期的数组。
这是我的代码:
function convert_to_csv($input_array, $output_file_name, $delimiter)
{
clearstatcache();
/** open raw memory as file, no need for temp files */
$temp_memory = fopen('php://memory', 'w');
/** loop through array */
foreach ($input_array as $line) {
/** default php csv handler **/
fputcsv($temp_memory, $line, $delimiter);
}
//echo '<pre>';
//print_r($temp_memory); exit;
/** rewrind the "file" with the csv lines **/
fseek($temp_memory, 0);
/** modify header to be downloadable csv file **/
header('Content-Type: application/csv');
header('Content-Disposition: attachement; filename="' . $output_file_name . '";');
/** Send file to browser for download */
fpassthru($temp_memory);
}
/** Array to convert to csv */
$array_to_csv = Array(
Array(12566,
'Enmanuel',
'Corvo'
),
Array(56544,
'John',
'Doe'
),
Array(78550,
'Mark',
'Smith'
)
);
clearstatcache();
convert_to_csv($array_to_csv, 'report.csv', ',');
【问题讨论】:
-
我在运行此代码时没有收到错误消息。我按预期下载了 csv。
-
当我在 WordPress 的插件环境中运行此代码时,我得到了 csv,它显示了列表中的所有 html 代码
-
代码按预期运行,并下载了一个 csv 文件。添加有关插件和 Wordpress 版本的信息,以帮助我们解决这个问题。
-
您是否启用了任何类型的调试(
WP_DEBUG设置为 true 或 XDebug)?如果是这样,这可能会导致您的 CSV 文件呈现无关的 HTML。