How to add the line delimiter(\n) in php

烈酒焚心 提交于 2020-06-27 04:14:08

问题


I have below code generating report with .dat file format.

public function export_dat() {
    /** check(s) **/
    if( ! $this->data) { throw new exception('unable to create xls: missing data'); }
    if( ! $this->path) { throw new exception('unable to create xls: missing path'); }
    /** output contents to dat **/
        ob_start();
        $df = fopen($this->path.'.dat', 'w');
        foreach ($this->data as $row) {
            fwrite($df, implode('|', $row));
        }
         fclose($df);
         /** return **/
         return $this->path;
}

And Output is

USERID|NAME|AGEuserId1|ABC|20userId2|BCD|30userId3|EFC|40

The data generated in single line. I am expecting below format:

USERID|NAME|AGE
userId1|ABC|20
userId2|BCD|30
userId3|EFC|40

Thanks advance.


回答1:


With your current code, the simplest is to just append it in the write part...

fwrite($df, implode('|', $row).PHP_EOL);

uses PHP_EOL for platform independance.

Or you could use fputcsv()...

fputcsv($df, $row, "|");

Just to note that if you definitely need to use it, "\n" will work the same in the output.



来源:https://stackoverflow.com/questions/62409089/how-to-add-the-line-delimiter-n-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!