Looking to Build/Redesign a Website or Blog ?

To speak to Rakshit, call +91 968 704 2303

[PHP] Export to Excel/CSV/TXT Problem with Special Chars

Hi Friends,

I am working with one Traditional Chinese website where I need to give Export to TXT functions. Actually my client is using some third party tool which accept .txt file only but txt file is CSV formatted. I have write down the code for export to txt and when i see the exported file, it shows me some weird characters. I have used almost all options for the Char supports and finally I found the one which fix my error.

Export to Excel Special Characters Code fixes

 ... Code to get data from database ...
 $str = "";
 $file_name = "csv_fomatted_txt_file.txt";
 $fh = fopen( $file_name , 'w' );
 foreach( $final_data_array as $k => $v_row ){
   $first = 0;
   foreach( $v_row as $v ){
      $str .= ( $first ? "\t" : "" ).$v;
      $first++;
   }
   $str .= "\r\n";
 }
 $str = chr(255).chr(254).mb_convert_encoding( $str, 'UTF-16LE', 'UTF-8' );
 fwrite( $fh, $str );
 fclose( $fh );

chr(255).chr(254).mb_convert_encoding( $str, ‘UTF-16LE’, ‘UTF-8’ ) line will fix your issue of special characters when you code export to excel or export to csv or export to txt. Remember, you need to change “UTF-16LE” as per your language. I have put “UTF-16LE” because i am working with Traditional Chinese language. You can find the appropriate as per your needs.

Share:

No Comments Yet.

Leave a Reply

Your email address will not be published.