How to extract data from csv file in PHP

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

    /**
     * @return mixed[]
     */
    public function csvToArray(string $delimiter, string $filename = ''): array
    {
        $data = [];
        if (file_exists($filename) && is_readable($filename)) {
            $header = null;
    
            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);
            }
        }
    
        return $data;
    }
    

提交回复
热议问题