eCalc
eCalc

Reputation: 21

PHP - Convert Unicode for CSV, e.g. chinese characters

with a form post we pass the data to a PHP script that creates a downloadable CSV for spread sheet programs (e.g. excel). The scipt below works perfect if no special char are passed. but passing special chars like chinese letters ends in the unicode....

Example: we send "你好世界" (hello world, unicode: 你好世界) via a form field post to this php script export.php

<?php //opens a download dialog, download by excel
header("Content-type: text/csv; charset=UTF-8");
header("Content-Disposition: attachment; filename=\"eCalc Results.csv\"");
echo html_entity_decode(urldecode($_POST["exportData"])); 
// returns unicode &#20320;&#22909;&#19990;&#30028;
?>

How can we convert this unicodes for CSV that the chinese letters are shown again correcly as 你好世界...?

here the example: http://s4a.ch/exporttest/hello.php

we searched the entire stackoverflow, but no conversion was successfull...

thanks for your help eCalc

Upvotes: 1

Views: 5094

Answers (2)

eCalc
eCalc

Reputation: 21

...found a solution:

first of all encode the sender side not with javascript encode() but with encodeURI() and use

<meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />

in the header.

...and here the export.php (with BOM inserted!!)

<?php

header("Content-Encoding: UTF-8"); 
header("Content-Disposition: attachment; filename=\"eCalc Results.csv\"");
header("Content-type: text/csv; charset=UTF-8");
echo "\xEF\xBB\xBF"; // first send the UTF-8 BOM for Excel

echo html_entity_decode(urldecode($_POST["exportData"]));
?>

Upvotes: 1

thedouglenz
thedouglenz

Reputation: 514

You might look into this section of the PHP documentation: http://php.net/manual/en/function.utf8-encode.php

Upvotes: 0

Related Questions