【发布时间】:2013-12-17 15:59:44
【问题描述】:
我有一个导出 CSV 文件的 PHP 脚本。然后我的用户在 Excel 中编辑文件,保存并重新上传。
如果他们在字段中键入欧元符号,则在上传文件时,欧元符号以及之后的所有内容都会丢失。我正在使用 str_getcsv 函数。
如果我尝试转换编码(比如转换为 UTF-8),欧元符号会消失,并且我会得到一个缺失的字符标记(通常由空白方块或菱形中的问号表示)。
如何将编码转换为 UTF-8,同时保留欧元符号(和其他非标准字符)?
编辑:
这是我的代码:
/**
* Decodes html entity encoded characters back to their original
*
* @access public
* @param String The element of the array to process
* @param Mixed The key of the current element of the array
* @return void
*/
public function decodeArray(&$indexValue, $key)
{
$indexValue = html_entity_decode($indexValue, ENT_NOQUOTES, 'Windows-1252');
}
/**
* Parses the contents of a CSV file into a two dimensional array
*
* @access public
* @param String The contents of the uploaded CSV file
* @return Array Two dimensional-array.
*/
public function parseCsv($contents)
{
$changes = array();
$lines = split("[\n|\r]", $contents);
foreach ($lines as $line) {
$line = utf8_encode($line);
$line = htmlentities($line, ENT_NOQUOTES);
$lineValues = str_getcsv($line);
array_walk($lineValues, 'decodeArray');
$changes[] = $lineValues;
}
return $changes;
我也尝试了以下代替 utf8_encode 函数:
iconv("Windows-1252", "UTF-8//TRANSLIT", $line);
还有就是:
$line = htmlentities($line, ENT_NOQUOTES, 'Windows-1252');
使用 utf8_encode 函数,可以从字符串中删除违规字符。使用任何其他方法,字符和字符之后的所有内容都会丢失。
示例:
字段值:“Promo € Mobile”
被解释为:“Promo Mobile”
【问题讨论】:
-
到目前为止你用过什么?尝试发布一些编码以帮助您。
-
欧元符号的什么字符被放入导出的 CSV?提示:在记事本中打开 csv 并查看它显示的内容。它可能会破坏 csv 中变量的封装,或者 csv 可能需要封装添加到其保存选项中。
-
为我工作:3v4l.org/9b3s3。认为输入 CSV 无效。你能把 csv 作为二进制文件上传到某个地方吗?
-
那么,CSV 到底是什么编码?
-
据我所知,编码是“Windows-1252”
标签: php excel csv character-encoding