Thursday, January 13, 2022

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

Issue

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() {
  
  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 $this->path;
}

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

public function export_dat() {
    
    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 $this->path;
}

Thanks advance for your help.


Solution

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

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


Answered By - IluTov

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.