search

Home  >  Q&A  >  body text

python - php exports csv problem with long text with line breaks

When exporting a csv file, some long text with line breaks will be automatically wrapped, but I want it to be line wrapped within the cell

Post code

$str = "操作人,操作,修改项,修改前,修改后,操作时间\n";
$str = iconv('utf-8','gb2312',$str);
while($r=$empire->fetch($sql))
{$data[]=$r;
    $name      = '"'.getUserName($r['uid']).'"'; //中文转码
    $action  = '"'.iconv('utf-8','gb2312',str_replace(array("\n","\r",'"'),array("//","//","'"),urldecode($r['action']))).'"';
    $time    = '"'.date('Y-m-d H:i:s',$r['time']).'"';
    $old     = '"'.str_replace(array("\n","\r",'"'),array("//","//","'"),urldecode($r['old'])).'"';
    $new     = '"'.str_replace(array("\n","\r",'"'),array("//","//","'"),urldecode($r['new'])).'"';
    $pro_name= getHierarchyName($r['type_id']);
    $name  =  $name ?  $name :'已删除或禁用';
    $str .= "{$name},{$action},{$pro_name},{$old},{$new},{$time}\n"; //用引文逗号分开
}
$file_name = $file_name? $file_name:'工作组操作日志';
$filename = $file_name.'.csv'; //设置文件名
export_csv($filename,$str);

I have tried string replacement and other things. Please advise

The problem is solved. A newline character appeared in a field that should not have a newline character. It’s so painful

某草草某草草2810 days ago1012

reply all(2)I'll reply

  • 天蓬老师

    天蓬老师2017-05-16 13:01:11

    Thanks for the invitation!

    Since I use my mobile phone to check the replies, I apologize for any typographical issues. If it is just a line break within the cell, it is okay to use double quotes plus r. If it is a single quote within the text, it will not parse the line break. I don’t know if I understand what you mean or not...

    reply
    0
  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-05-16 13:01:11

    I just tested it, the content of the file hello.csv is in the following form

    hello,"nihao
    hehe"
    haha,"buhao
    woca, nihao"

    can be line-wrapped without affecting the display results,


    You’re welcome. In addition, it is recommended that the subject go to Baidu to learn about the usage of the csv file content format. It is very simple, so I will not expand it.

    reply
    0
  • Cancelreply