我正在编写一个插件,我需要用户能够下载动态创建的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);
希望它有所帮助!
答案 0 :(得分:0)
我已根据您的问题阅读了评论,但我真的不明白,为什么要打开文件,保存对$fp
的引用,然后从您的CSV中回显$data
,而不是使用函数{{1 }}:
fputs
试试这个:
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);
或者可以选择存储CSV数据;你可以使用这个功能:
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 );
fputs($fp, $data);
fclose($fp);
答案 1 :(得分:0)
我发布这个作为答案,因为这解决了我的问题。 fputs回显到输出缓冲区的问题是另一个问题的主题。
问题是数据是作为单引号字符串输出的,所以我不得不用双引号替换单引号返回。
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);
希望它有所帮助!