php – fgetcsv正在吃一个字符串的第一个字母,如果它是一个变音符号

我正在将Excel生成的CSV文件中的内容导入 XML文档,如:
$csv = fopen($csvfile,r);
$words = array();

while (($pair = fgetcsv($csv)) !== FALSE) {
    array_push($words,array('en' => $pair[0],'de' => $pair[1]));
}

插入的数据是英语/德语表达.

我将这些值插入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();

这工作正常,但我遇到一个非常奇怪的问题.当一个字符串的第一个字母是变音符号(如Österreich或Ägypten)时,该字符将被省略,从而产生gypten或sterreich.如果变音符号位于字符串(RussischeFö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: https://stackoverflow.com/a/7498886/797194

foreach ($lines as $line) {
    array_push($words,getCSVValues($line));
}

getCSVValues来自here,需要处理这样的CSV行(逗号!):

"I'm a string,what should I do when I need commas?",Howdy there

看起来像:

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,$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;

}

相当多的解决方法,但似乎工作正常.

编辑:

还有一个filed bug,显然这取决于区域设置.

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...