write utf-8 characters to file with fputcsv in php

61,417

Solution 1

Try this:

$df = fopen($filepath, 'w');
fprintf($df, chr(0xEF).chr(0xBB).chr(0xBF));
fputcsv($df, array($coupon->code, $discount->label));

the line fprintf($df, chr(0xEF).chr(0xBB).chr(0xBF)); writes file header for correct encoding.

Solution 2

Try this also:

$df = fopen($filepath, 'w');
$array = array($coupon->code, $discount->label);
$array = array_map("utf8_decode", $array);
fputcsv($df, $array);

Solution 3

If you want make a UTF-8 file for excel, use this simple solution:

$fp = fopen($filename, 'w');

//add BOM to fix UTF-8 in Excel 
fputs($fp, $bom =( chr(0xEF) . chr(0xBB) . chr(0xBF) ));

See the original answer here on the official PHP page.

Share:
61,417
Yuseferi
Author by

Yuseferi

Find more about my on About Me

Updated on July 09, 2022

Comments

  • Yuseferi
    Yuseferi almost 2 years

    I want to try write Persian character in CSV file in PHP, I am using fputcsv function but how can write UTF-8 character to CSV file with fputcsv?

    Part of my code:

    $df = fopen($filepath, 'w');
    fputcsv($df, array($coupon->code, $discount->label));
    
  • mwfearnley
    mwfearnley almost 8 years
    What does this answer do?
  • Solrac
    Solrac over 7 years
    This will decode your UTF8 strings into single byte ISO-8859-1. This NOT what the OP was asking for.
  • Faris Rayhan
    Faris Rayhan over 6 years
    You also have to take consideration in excel perspective. Make sure the excel already encoded in UTF-8
  • Phuong
    Phuong over 6 years
    Good solution. Thanks Hardy!
  • Chinmay235
    Chinmay235 about 6 years
    @FarisRayhan Same things here.. :(
  • Ahmad Baktash Hayeri
    Ahmad Baktash Hayeri about 5 years
    Could you please explain what the three characters are and what is their purpose in fixing the UTF8 problem?
  • Herbert Van-Vliet
    Herbert Van-Vliet over 4 years
    @AhmadBaktashHayeri those bytes make up the Byte Order mark (BOM) for UTF-8
  • Ali
    Ali over 3 years
    My hero, saved my day :-*
  • Ross
    Ross over 3 years
    This is clearer in my opinion and leaves the work to be done by utf8_decode and not requiring the reader to obey the BOM.
  • rutex
    rutex about 2 years
    This works great but in my case it makes some fields not to be printed to the excel file. Any idea why is that?