Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP fputcsv encoding

I create csv file with fputcsv. I want csv file to be in windows1251 ecnding. But can't find the solution. How can I do that? Cheers

like image 368
nyanev Avatar asked Sep 19 '12 05:09

nyanev


People also ask

How does PHP Fputcsv work?

fputcsv() formats a line (passed as a fields array) as CSV and writes it (terminated by a newline) to the specified file stream .

How to write to csv file in PHP?

To convert an array into a CSV file we can use fputcsv() function. The fputcsv() function is used to format a line as CSV (comma separated values) file and writes it to an open file.

How do I add a new row to an existing CSV file in PHP?

Append a new row to the existing CSV file using writerOpen your existing CSV file in append mode Create a file object for this file. Pass this file object to csv.


2 Answers

It's Working: Enjoy
use this before fputcsv:

$line = array_map("utf8_decode", $line);
like image 89
Arslan Tabassum Avatar answered Nov 15 '22 23:11

Arslan Tabassum


Default encoding for an excel file is machine specific ANSI, mainly windows1252. But since you are creating that file and maybe inserting UTF-8 characters, that file is not going to be handled ok.

You could use iconv() when creating the file. Eg:

function encodeCSV(&$value, $key){
    $value = iconv('UTF-8', 'Windows-1252', $value);
}
array_walk($values, 'encodeCSV');
like image 22
Mihai Iorga Avatar answered Nov 15 '22 22:11

Mihai Iorga