CSV to JSON with PHP?

前端 未结 6 1431
遥遥无期
遥遥无期 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

    None of these answers work with multiline cells, because they all assume a row ends with '\n'. The builtin fgetcsv function understands that multiline cells are enclosed in " so it doesn't run into the same problem. The code below instead of relying on '\n' to find each row of a csv lets fgetcsv go row by row and prep our output.

    function csv_to_json($file){
    
        $columns = fgetcsv($file); // first lets get the keys.
        $output = array(); // we will build out an array of arrays here.
    
        while(!feof($file)){ // until we get to the end of file, we'll pull in a new line
            $line = fgetcsv($file); // gets the next line
            $lineObject = array(); // we build out each line with our $columns keys
            foreach($columns as $key => $value){
                $lineObject[$value] = $line[$key];
            }
            array_push($output, $lineObject);
        }
        return json_encode($output); // encode it as json before sending it back
    }
    

提交回复
热议问题