我正在编写一个插件,我需要用户能够下载动态创建的 csv(我不想用完服务器空间)。我将需要打印到 csv 的文本固定在表单中的隐藏元素中,然后使用 fopen 和 fclose 回显并创建 csv。问题是没有解析新行。我尝试添加斜杠、用双引号关闭变量以及输出缓冲。我还将 auto_detect_line_endings 设置为 true。这是我的代码。
header('Content-Type: application/excel');
header('Content-Disposition: attachment; filename="sample.csv"');
$fp = fopen('php://output', 'w');
$data = $_POST['csv_holder'];
echo $data;
fclose($fp);
和html:
<form id = 'wcds_$post_id_csv_download' action ='$download_file' method='post'><input type ='hidden' name = 'csv_holder' id ='wcds_download_csv_$post_id_value' value ='$wcds_item_details_string'><input type ='submit' id ='wcds_download_csv_$post_id' class ='wcds_download_button'</form>
示例$wcds_item_details_string
:1,2,3\r\n4,5,6\r\n7,8,9
$wcds_item_details_string = get_the_content();
//sanitise for html
$wcds_item_details_string = htmlspecialchars ( $wcds_item_details_string, ENT_QUOTES );
尝试字符串替换:
$replace = '\';
$backslash = '\\';
$wcds_item_details_string = str_replace( $backslash, $replace, $wcds_item_details_string );
弄清楚了,数据库将变量作为单引号字符串返回。我只需要使用字符串替换将换行符更改为双引号。最终代码:
header('Content-Type: application/excel');
header('Content-Disposition: attachment; filename="sample.csv"');
$fp = fopen('php://output', 'w');
$data = $_POST['csv_holder'];
$data= str_replace( '\r\n', "\r\n", $data );
echo "{$data}";
fclose($fp);
希望它可以帮助某人!