php – 将CSV转换为数组

前端之家收集整理的这篇文章主要介绍了php – 将CSV转换为数组前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有这个数组与机场代码和城市名称(约3500行).
code,city
"Abilene,TX ",ABI
"Adak Island,AK ",ADK
"Akiachak,KKI
"Akiak,AKI
"Akron/Canton,OH ",CAK
"Akuton,KQA
"Alakanuk,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
)
如果是换行符,您可以尝试使用暴力方法
$file = file_get_contents("test.csv");
$data = array_map("str_getcsv",preg_split('/\r*\n+|\r+/',$file));
print_r($data);

str_getcsv可通过PHP 5.3获得,或通过upgradephpPHP_Compat作为手册中的解决方法.

原文链接:https://www.f2er.com/php/138890.html

猜你在找的PHP相关文章