在PHP中读取具有引号之间字段的CSV文件

时间:2015-02-09 20:50:04

标签: php csv

我有一个csv文件,其中包含以下结构:

"Trussville","L01","2352","Flatbed Truck"
"Trussville","L01","2336","Tote Truck"
"Trussville","L01","2379","Combo Truck"
"Trussville","L01","2238","Tankwagon (Glycol Truck)"
"Trussville","L01","2306","Combo Truck"
"Trussville","L01","2364","Tankwagon 2690 gal (650, 550, 400, 390, 350, 350)"
"Trussville","L01","2380","Combo Truck"
"Trussville","L01","2382","Tankwagon 3500 gal (900, 600, 400, 400, 500, 700)"

我使用以下函数解析和读取csv数据如下:

function fncRead($csvFile){
     //Open the file in read mode
    $file_handle = fopen($csvFile, 'r');
    //Go through a loop
    while (!feof($file_handle) ) {
        // get data using fgetcsv and push to an array
        $line_of_text[] = fgetcsv($file_handle, 1024);
    }
    //Close the file after reading
    fclose($file_handle);
    //return the array of data
    return $line_of_text;
}

我得到的结果如下:

Array
(
    [0] => Array
        (
            [0] => Trussville
            [1] => L01
            [2] => 2352
            [3] => Flatbed Truck
"Trussville"
            [4] => L01
            [5] => 2336
            [6] => Tote Truck
"Trussville"
            [7] => L01
            [8] => 2379
            [9] => Combo Truck
"Trussville"
            [10] => L01
            [11] => 2238
            [12] => Tankwagon (Glycol Truck)
"Trussville"
            [13] => L01
            [14] => 2306
            [15] => Combo Truck
"Trussville"
            [16] => L01
            [17] => 2334
            [18] => Tote Truck
"Trussville"
            [19] => L01
            [20] => 2337
            [21] => 1000 gallon def compatment
"Trussville"
            [22] => L01
            [23] => 2338
            [24] => DO NOT USE
"Trussville"
            [25] => L01
            [26] => 2364
            [27] => Tankwagon 2690 gal (650, 550, 400, 390, 350, 350)
"Trussville"

..................

我想要的是:

Array
(
    [0] => Array
        (
            [0] => Trussville
            [1] => L01
            [2] => 2352
            [3] => Flatbed Truck
        ),
   [1] => Array
        (
            [0] => Trussville
            [1] => L01
            [2] => 2336
            [3] => Tote Truck
        ),
.....

我该怎么办呢?

2 个答案:

答案 0 :(得分:2)

引用PHP docs page for the fgetcsv() function

  

注意:如果在Macintosh计算机上读取文件或由Macintosh计算机创建文件时PHP无法正确识别行结尾,则启用auto_detect_line_endings运行时配置选项可能有助于解决问题。

答案 1 :(得分:1)

您的文件似乎缺少换行符(\ r \ n)

尝试以下操作,看看是否得到相同的结果。如果你这样做,那肯定是文件。如果它有效,那么可能有一些关于使用f方法处理文件的事情。

function fncRead($csvFile){
    foreach(file($csvFile) as $value)
    {
            $$line_of_text[] = str_getcsv($value);

    }
    return $line_of_text;
}