How to extract data from csv file in PHP

前端 未结 11 1469
醉酒成梦
醉酒成梦 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:08

    Maybe my code solves your problem:

    // Parse all content from csv file and generate array from line.
    function csv_content_parser($content) {
      foreach (explode("\n", $content) as $line) {
        // Generator saves state and can be resumed when the next value is required.
        yield str_getcsv($line);
      }
    }
    // Get content from csv file.
    $content = file_get_contents('your_file.csv');
    // Create one array from csv file's lines.
    $data = array();
    foreach (csv_content_parser($content) as $fields) {
      array_push($data, $fields);
    }
    

    In result you have an array with all values from csv. It would be something like:

    Array
    (
        [0] => Array
            (
                [0] => text, with commas
                [1] => another text
                [2] => 123
                [3] => text
                [4] => 5
            )
    
        [1] => Array
            (
                [0] => some without commas
                [1] => another text
                [2] => 123
                [3] => text
            )
    
        [2] => Array
            (
                [0] => some text, with comma,s or no
                [1] =>  NULL 
                [2] => 123
                [3] => text
            )
    
    )
    

提交回复
热议问题