How to extract data from csv file in PHP

前端 未结 11 1463
醉酒成梦
醉酒成梦 2020-11-22 07:36

I have a csv file which looks like this

$lines[0] = \"text, with commas\", \"another text\", 123, \"text\",5;
$lines[1] = \"some without commas\", \"another          


        
11条回答
  •  温柔的废话
    2020-11-22 08:09

    You could use something like https://github.com/htmlburger/carbon-csv that allows column mapping:

    $csv = new \Carbon_CSV\CsvFile('path-to-file/filename.csv');
    $csv->set_column_names([
        0 => 'first_name',
        1 => 'last_name',
        2 => 'company_name',
        3 => 'address',
    ]);
    foreach ($csv as $row) {
        print_r($row);
    }
    

    The result of the below code would be something like:

    Array
    (
        [0] => Array
            (
                [first_name] => John
                [last_name] => Doe
                [company_name] => Simple Company Name
                [address] => Street Name, 1234, City Name, Country Name
            )
        [1] => Array
            (
                [first_name] => Jane
                [last_name] => Doe
                [company_name] => Nice Company Name
                [address] => Street Name, 5678, City Name, Country Name
            )
    )
    

    Another library that does the same thing(and much more) is http://csv.thephpleague.com/9.0/reader/

提交回复
热议问题