PHP CSV string to array

前端 未结 10 1307
攒了一身酷
攒了一身酷 2020-11-27 02:41

I\'m trying to parse a CSV string to an array in PHP. The CSV string has the following attributes:

Delimiter: ,
Encl         


        
10条回答
  •  广开言路
    2020-11-27 03:38

    I have used following function to parse csv string to associative array

    public function csvToArray($file) {
        $rows = array();
        $headers = array();
        if (file_exists($file) && is_readable($file)) {
            $handle = fopen($file, 'r');
            while (!feof($handle)) {
                $row = fgetcsv($handle, 10240, ',', '"');
                if (empty($headers))
                    $headers = $row;
                else if (is_array($row)) {
                    array_splice($row, count($headers));
                    $rows[] = array_combine($headers, $row);
                }
            }
            fclose($handle);
        } else {
            throw new Exception($file . ' doesn`t exist or is not readable.');
        }
        return $rows;
    }
    

    if your csv file name is mycsv.csv then you call this function as:

    $dataArray = csvToArray(mycsv.csv);
    

    you can get this script also in http://www.scriptville.in/parse-csv-data-to-array/

提交回复
热议问题