How to export file in .dat or .txt format using php

心已入冬 提交于 2020-06-09 05:52:39

问题


I have function export_csv()to export file as .csv format. I want to change .dat or .txt format instead of .csv

Current code:

public function export_csv() {
  /** 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 conetnts to csv **/
       ob_start();
       $df = fopen($this->path.'.csv', 'w');
       foreach ($this->data as $row) {
       fputcsv($df, $row);
       }
      fclose($df);
      /** return **/
      return $this->path;
}

I have tried below code. but .dat file was blank. The file size 0

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, $row);
        }
         fclose($df);
         /** return **/
         return $this->path;
}

Thanks advance for your help.


回答1:


fwrite takes a string, not an array. Try something like this:

fwrite($df, implode(', ', $row));


来源:https://stackoverflow.com/questions/62169939/how-to-export-file-in-dat-or-txt-format-using-php

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