将CSV转换为数组

时间:2011-09-21 15:23:21

标签: php arrays csv fgetcsv

我有一个机场代码和城市名称(大约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
)

3 个答案:

答案 0 :(得分:18)

如果是换行符,您可以尝试使用强力方法:

$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手册中的解决方法。

答案 1 :(得分:3)

试试这个: -

ini_set('auto_detect_line_endings', TRUE);/// (PHP's detection of line endings) write at the top.


$csvrows = array_map('str_getcsv', file($filepath));
$csvheader = array_shift($csvrows);
$csv = array();
foreach ($csvrows as $row) {
   $csv[] = array_combine($csvheader, $row);
}

答案 2 :(得分:1)

尝试 -

$csv = array();

if (($file = fopen('test.csv', 'r')) === false) {
    throw new Exception('There was an error loading the CSV file.');
} else {  
   while (($line = fgetcsv($file, 1000)) !== false) {
      $csv[] = $line;
   }
   fclose($handle);
}