我有一个包含机场代码和城市名称的数组(大约3500行)。
code,city
"Abilene, TX ",ABI
"Adak Island, AK ",ADK
"Akiachak, AK ",KKI
"Akiak, AK ",AKI
"Akron/Canton, OH ",CAK
"Akuton, AK ",KQA
"Alakanuk, AK ",AUK
"Alamogordo, NM ",ALM
我需要把这个文件转换成一个PHP数组。这是我目前为止的代码:
if(($handle = fopen('test.csv', 'r')) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ',', '"')) !== FALSE) {
echo '<pre>';
print_r($data);
echo '</pre>';
}
fclose($handle);
}
虽然我为fgetcsv函数设置了分隔符和包围字符,但结果如下:
Array
(
[0] => code
[1] => city
"Abilene
[2] => TX "
[3] => ABI
"Adak Island
[4] => AK "
[5] => ADK
"Akiachak
[6] => AK "
[7] => KKI
"Akiak
[8] => AK "
[9] => AKI
"Akron/Canton
[10] => OH "
[11] => CAK
"Akuton
[12] => AK "
[13] => KQA
"Alakanuk
[14] => AK "
[15] => AUK
"Alamogordo
[16] => NM "
[17] => ALM
)
4条答案
按热度按时间lymnna711#
如果是换行符,你可以尝试使用蛮力方法:
str_getcsv
可在PHP 5.3中使用,或者作为手册中的解决方法,通过upgradephp或PHP_Compat使用。tvokkenx2#
试试这个:-
atmip9wb3#
尝试-
u1ehiz5o4#
要解决这个问题,可以尝试在用
fgetcsv
解析每行之前删除其中的空格。在更新后的代码中,我们使用
fgets
读取文件的每一行,然后进行修剪以删除任何前导或尾随空格。最后,使用str_getcsv
解析CSV
数据。