dongzheng4556 2013-05-03 11:44
浏览 227

正确编码PHPexcel的CSV文件

I have a Json, decode it, write it in a CSV file with PHP, convert the CSV to .xls with the aid of PHPexcel

The goal is to export from a JSON into an excel file correctly. I am having trouble with encoding and mainly with Excel for Mac 2011 which does not support UTF-8 CSV files: link If I preview it (spacebar) on my mac it looks well encoded. The trouble is the excel.

First the code for the CSV:

$file_csv = fopen('files/file.csv', 'w');

then the JSON:

$response_data = json_decode($connection->response['response'], true);
foreach ($response_data as $value)
  {
  //take the data I have 10 strings here in reality
  $text_lang = $value['lang'];
  $date = $value['date'];
  //insert into the csv
  $details = array($text_lang, $date );
  fputcsv($file_csv, $details);
};
fclose($file_csv);

Now if I import this CSV with the excel I have trouble with UTF-8. If I convert it with a text editor e.g. Textmate to UTF-16LE, and then import it to Excel everything is smooth.

And the PHPExcel code to create the .xls from here:

$objReader = PHPExcel_IOFactory::createReader('CSV');
$objPHPExcel = $objReader->load('files/file.csv');  
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('files/summary.xls');

The summary.xls is broken on UTF-8 and when opening it requires to be repaired.


My first attempt was to convert the above file.csv into UTF-16LE in PHP to see if that will be ok with the excel. I used iconv before fputcsv and the excel showed Chinese words...

Now I want to encode the csv file to UTF-16LE and load it well with PHPExcel. I used the following lines and didn't work. Probably because the .csv I had created with the incov was partially (?) UTF-8 and UTF-16LE.

$objReader->setInputEncoding('UTF-16LE');
$objPHPExcel = $objReader->load('file.csv');

The goal is to render the data from the JSON into a .xls (or .xlxs) document without encoding problems on excel.

  • 写回答

1条回答 默认 最新

  • drwurqczo39355510 2015-10-14 14:16
    关注
    $objReader->setInputEncoding('');
    
    $objPHPExcel = $objReader->load('file.csv');
    

    this worked well for me.

    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?