m90*_*m90 8 php xml csv diacritics character-encoding
我将内容从Excel生成的CSV文件导入XML文档,如:
$csv = fopen($csvfile, r);
$words = array();
while (($pair = fgetcsv($csv)) !== FALSE) {
array_push($words, array('en' => $pair[0], 'de' => $pair[1]));
}
Run Code Online (Sandbox Code Playgroud)
插入的数据是英语/德语表达.
我将这些值插入XML结构并输出XML,如下所示:
$dictionary = new SimpleXMLElement('<dictionary></dictionary>');
//do things
$dom = dom_import_simplexml($dictionary) -> ownerDocument;
$dom -> formatOutput = true;
header('Content-encoding: utf-8'); //<3 UTF-8
header('Content-type: text/xml'); //Headers set to correct mime-type for XML output!!!!
echo $dom -> saveXML();
Run Code Online (Sandbox Code Playgroud)
这工作正常,但我遇到一个非常奇怪的问题.当String的第一个字母是变音符号(如in Österreich或Ägypten)时,将省略该字符,从而产生gypten或sterreich.如果变音符号位于String(Russische Föderation)的中间,则会正确传输.对于喜欢ß或类似的é东西也是如此.
所有文件均采用UTF-8编码,并以UTF-8格式提供.
对我来说,这似乎很奇怪,而且我可能会错过一些东西,这里有很多聪明的人.
好吧,这似乎是 中的一个错误fgetcsv。
我现在正在自己处理 CSV 数据(有点麻烦),但它正在工作,而且我根本没有任何编码问题。
这是我正在做的(尚未优化的版本):
$rawCSV = file_get_contents($csvfile);
$lines = preg_split ('/$\R?^/m', $rawCSV); //split on line breaks in all operating systems: http://stackoverflow.com/a/7498886/797194
foreach ($lines as $line) {
array_push($words, getCSVValues($line));
}
Run Code Online (Sandbox Code Playgroud)
来自getCSVValues此处,需要处理这样的 CSV 行(逗号!):
"I'm a string, what should I do when I need commas?",Howdy there
Run Code Online (Sandbox Code Playgroud)
看起来像:
function getCSVValues($string, $separator=","){
$elements = explode($separator, $string);
for ($i = 0; $i < count($elements); $i++) {
$nquotes = substr_count($elements[$i], '"');
if ($nquotes %2 == 1) {
for ($j = $i+1; $j < count($elements); $j++) {
if (substr_count($elements[$j], '"') %2 == 1) { // Look for an odd-number of quotes
// Put the quoted string's pieces back together again
array_splice($elements, $i, $j-$i+1,
implode($separator, array_slice($elements, $i, $j-$i+1)));
break;
}
}
}
if ($nquotes > 0) {
// Remove first and last quotes, then merge pairs of quotes
$qstr =& $elements[$i];
$qstr = substr_replace($qstr, '', strpos($qstr, '"'), 1);
$qstr = substr_replace($qstr, '', strrpos($qstr, '"'), 1);
$qstr = str_replace('""', '"', $qstr);
}
}
return $elements;
}
Run Code Online (Sandbox Code Playgroud)
这是一个相当多的解决方法,但似乎效果很好。
编辑:
还有一个已提交的错误,显然这取决于区域设置。
| 归档时间: |
|
| 查看次数: |
2947 次 |
| 最近记录: |