PHP Array to CSV in UTF-8 read by MS Excel
To people who are looking for a PHP script that can convert an array (mostly multi-dimensional array) to CSV in UTF-8, here is the code and file for you to download:
PHP Array To CSV Read By MS Excel in UTF-8
Credit to Jérôme Jaglale, what I am looking for is a CodeIgniter solution to convert array to CSV, but it can also be used in non-CI PHP application. This is not a class, just a function (Helper). The full code below:
PHP Array To CSV Read By MS Excel in UTF-8
Credit to Jérôme Jaglale, what I am looking for is a CodeIgniter solution to convert array to CSV, but it can also be used in non-CI PHP application. This is not a class, just a function (Helper). The full code below:
if(!function_exists('array_to_csv')){ function array_to_csv($array, $download = ""){ // http://stackoverflow.com/questions/13108157/php-array-to-csv if(empty($download)){ $res = array(); foreach($array as $arr) { $res[] = implode(',', $arr); } return $res; }else{ $output = fopen("php://output",'w') or die("Can't open php://output"); // http://stackoverflow.com/questions/4348802/how-can-i-output-a-utf-8-csv-in-php-that-excel-will-read-properly header('Content-Encoding: UTF-8'); header("Content-Type:application/csv"); header("Content-Disposition:attachment;filename=".$download); echo "\xEF\xBB\xBF"; foreach($array as $arr) { array_map('iconv_utf8_big5', $arr); fputcsv($output, $arr); } fclose($output) or die("Can't close php://output"); } } function iconv_utf8_big5($str){ return @iconv(mb_detect_encoding($str, mb_detect_order(), true), "UTF-8", $str); } }Hope it helps someone.
Comments