CSV to JSON with PHP?

前端 未结 6 1432
遥遥无期
遥遥无期 2020-12-31 13:48

I need to convert a CSV file to JSON on the server using PHP. I am using this script which works:

function csvToJSON($csv)          


        
6条回答
  •  甜味超标
    2020-12-31 14:01

    I modified the answer in the question to use the first line of the CSV for the array keys. This has the advantage of not having to hard-code the keys in the function allowing it to work for any CSV with column headers and any number of columns.

    Here is my modified version:

    function csvToJson($csv) {
        $rows = explode("\n", trim($csv));
        $data = array_slice($rows, 1);
        $keys = array_fill(0, count($data), $rows[0]);
        $json = array_map(function ($row, $key) {
            return array_combine(str_getcsv($key), str_getcsv($row));
        }, $data, $keys);
    
        return json_encode($json);
    }
    

提交回复
热议问题