How to extract data from csv file in PHP

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

    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);
    

提交回复
热议问题