How to extract data from csv file in PHP

2018-12-31 12:10发布

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 text", 123, "text";
$lines[2] = "some text with commas or no",, 123, "text";

And I would like to have a table:

$t[0] = array("text, with commas", "another text", "123", "text","5");
$t[1] = array("some without commas", "another text", "123", "text");
$t[2] = array("some text, with comma,s or no", NULL , "123", "text");

If I use split($lines[0],",") I'll get "text" ,"with commas" ... Is there any elegant way to do it?

标签: php csv split
9条回答
一个人的天荒地老
2楼-- · 2018-12-31 12:36

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/

查看更多
骚的不知所云
3楼-- · 2018-12-31 12:38

Suppose you have a create a function for same things, Then it should look like

function csvtoarray($filename='', $delimiter){

    if(!file_exists($filename) || !is_readable($filename)) return FALSE;
    $header = NULL;
    $data = array();

    if (($handle = fopen($filename, 'r')) !== FALSE ) {
        while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
        {   
            if(!$header){
                $header = $row;
            }else{
                $data[] = array_combine($header, $row);
            }
        }
        fclose($handle);
    }
    if(file_exists($filename)) @unlink($filename);

    return $data;
}

$data = csvtoarray('file.csv', ',');

print_r($data);
查看更多
看风景的人
4楼-- · 2018-12-31 12:40

You can use fgetcsv to parse a CSV file without having to worry about parsing it yourself.

Example from PHP Manual:

$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        echo "<p> $num fields in line $row: <br /></p>\n";
        $row++;
        for ($c=0; $c < $num; $c++) {
            echo $data[$c] . "<br />\n";
        }
    }
    fclose($handle);
}
查看更多
有味是清欢
5楼-- · 2018-12-31 12:41

When you want to keep the index (first line) for multidimensional result array, you can use:

$delim      = ';';
$csvFile    = file($csv_file);
$firstline  = str_getcsv($csvFile[0], $delim);
$data       = array();
foreach ($csvFile as $line) {
    $line   = str_getcsv($line, $delim);
    $data[] = array_combine($firstline, $line);
}
查看更多
残风、尘缘若梦
6楼-- · 2018-12-31 12:45

In addition to Matt's suggestion, you can also use SplFileObject to read in the file:

$file = new SplFileObject("data.csv");
$file->setFlags(SplFileObject::READ_CSV);
$file->setCsvControl(',', '"', '\\'); // this is the default anyway though
foreach ($file as $row) {
    list ($fruit, $quantity) = $row;
    // Do something with values
}

source: http://de.php.net/manual/en/splfileobject.setcsvcontrol.php

查看更多
笑指拈花
7楼-- · 2018-12-31 12:48

you can read the data using the following function.

  function readCSV() {
    $csv = array_map('str_getcsv', file('data.csv'));
    array_shift($csv); //remove headers


}

http://www.pearlbells.co.uk/how-to-sort-a1a2-z9z10aa1aa2-az9az10-using-php/

查看更多
登录 后发表回答