doujiepin5547 2013-11-05 05:05
浏览 29
已采纳

Php没有解析从GET请求获得的变量中的新行

I am writing a plugin in which I need the user to be able to download a csv created on the fly (I don't want to use up server space). I have the text I need to print to csv pinted in a hidden element in a form, which I then echo and create csv using fopen and fclose. The problem is that new lines are not being parsed. I have tried adding slashes, closing the variable in double quotes, and output buffering. I have also set auto_detect_line_endings to true. Here is my code.

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);

and the 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>

example $wcds_item_details_string: 1,2,3 4,5,6 7,8,9

$wcds_item_details_string = get_the_content();
    //sanitise for html
    $wcds_item_details_string = htmlspecialchars ( $wcds_item_details_string, ENT_QUOTES );

Tried string replace :

$replace = '&#92';
    $backslash = '\\';
    $wcds_item_details_string = str_replace( $backslash, $replace, $wcds_item_details_string );

Figured it out, the database was returning the variable as a single quoted string. I just had to use string replace to change the line breaks to double quoted. Final code:

header('Content-Type: application/excel');
header('Content-Disposition: attachment; filename="sample.csv"');
$fp = fopen('php://output', 'w');
$data = $_POST['csv_holder'];
    $data= str_replace(  '
', "
", $data );
echo "{$data}";
fclose($fp);

Hope it helps someone!

  • 写回答

2条回答 默认 最新

  • dongri1989 2013-11-13 10:30
    关注

    I'm posting this as the answer, as this was what solved my problem. The issue with fputs over echoing to the output buffer is a subject for another question.

    The problem was the data was being output as a single quoted strings, so I had to replace the single quoted returns with double quoted ones.

    header('Content-Type: application/excel');
    header('Content-Disposition: attachment; filename="sample.csv"');
    $fp = fopen('php://output', 'w');
    $data = $_POST['csv_holder'];
    $data= str_replace(  '
    ', "
    ", $data );
    echo "{$data}";
    fclose($fp);
    

    Hope it helps someone!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度