0

I export csv in php as:

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

            foreach ($list as $fields) {
                if(!empty($fields))
                fputcsv($fp, $fields);
                else
                fputcsv($fp, ' ');

            }
            $fp = chr(255).chr(254).mb_convert_encoding($fp,"UTF-16LE","UTF-8"); 
            fclose($fp);

When i open csv, font UTF_8 is error. Ex: 防本部コー show in file csv: æ¶ˆé˜²æœ¬éƒ¨ă‚³ăƒ¼ăƒ‰

Can I help you? Thanks

3 Answers 3

1

This has been discussed here:

How can I output a UTF-8 CSV in PHP that Excel will read properly?

You might also want to check your CSV in an alternative text editor to rule out the editor.

Sign up to request clarification or add additional context in comments.

Comments

1

$fp is a pointer resource to a file. It is not a string, you cannot do this:

$fp = chr(255).chr(254).mb_convert_encoding($fp,"UTF-16LE","UTF-8"); 

To write UTF-16 data to the file, you need to convert it before writing it, not after the fact:

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

fwrite($fp, chr(255).chr(254));

foreach ($list as $fields) {
    foreach ($fields as &$field) {
        $field = mb_convert_encoding($field, 'UTF-16LE', 'UTF-8');
    }
    fputcsv($fp, $fields);
}

fclose($fp);

Don't know if this actually outputs the data you need, but it fixes the obvious error.

Comments

0

Try this function will work:

public static function exportCSVFile($data = array(), $headers = array(), $delimiter = ",", $csvfilename = "CSVFile") {
        ob_clean();
        ob_start();
        $csvfilename = $csvfilename . "_" . date("Y_m_d_h_i_s") . ".csv";
        $file_handler = fopen("php://output", 'w');
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Content-Type: application/csv");
        //header( "Content-Type: application/csv;charset=utf-8" );
        header("Content-Disposition: attachment;filename={$csvfilename}");
        header("Content-Transfer-Encoding: binary");
        foreach ($data as $fields) {
            $_str = implode($delimiter, $fields);
            $fields = explode($delimiter, utf8_decode($_str));
            fputcsv($file_handler, $fields, $delimiter, $enclosure = '"');
        }
        fclose($file_handler);
        ob_flush();
        exit();
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.