CSV to JSON with PHP?

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

    I recommend using Coseva (a csv parsing library) and using the built in toJSON() method.

    <?php
    
    // load
    require('../src/CSV.php');
    
    // read
    $csv = new Coseva\CSV('path/to/my_csv.csv');
    
    // parse
    $csv->parse();
    
    // disco
    echo $csv->toJSON();
    
    0 讨论(0)
  • 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);
    }
    
    0 讨论(0)
  • 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
    }
    
    0 讨论(0)
  • 2020-12-31 14:13

    You could probably reduce the overhead by removing all the spaces and \n's. But that's in your note.

    You could increase the performance by skipping the preg_replace and passing a boolean that would turn it on and off.

    Other than that, the variable unrolling of your var[1-10] actually is good, as long as there are always ten varaibles.

    The explode and the foreach approach are just fine.

    0 讨论(0)
  • 2020-12-31 14:18

    Some tips...

    • If you have URL opening enabled for fopen() and wrappers, you can use fgetscsv().
    • You can build an array of the CSV, and then convert it with PHP's native json_encode().
    • The correct mime type for JSON is application/json.
    0 讨论(0)
  • 2020-12-31 14:26

    Well there is the json_encode() function, which you should use rather than building up the JSON output yourself. And there is also a function str_getcsv() for parsing CSV:

    $array = array_map("str_getcsv", explode("\n", $csv));
    print json_encode($array);
    

    You must however adapt the $array if you want the JSON output to hold named fields.

    0 讨论(0)
提交回复
热议问题