How to Convert CSV to JSON Using a PHP Function

In this tutorial we will understand how we can use a small piece of code written in PHP and convert CSV files to JSON. For that we are going to use header rows as keys. 

First of all we need to understand that we use JSON and CSV as data storing formats and JSON is used on a wider scale as compared to CSV owing to its ease of use and readability. Every other web service uses it. 

So if you want to learn how to convert CSV to JSON file So when while converting CSV to JSON we need to be a little careful because we want our json file to be duly formatted as well by using key:value pairs. 

You should know that we cannot convert CSV to JSON directly. The CSV header row will be used as keys and subsequent rows as value to construct our json string. This way of converting it is very useful to get the desired results by using header row as keys. 

Converting CSV to JSON using PHP

Let’s see the following example where we will take a CSV file to convert into JSON with a header and rows with the help of PHP script

1,Suki Burks,Developer,$114500 
2,Fred Zupers,Technical Author,$145000 
3,Gavin Cortez,Team Leader,$235500

See the following PHP function which will be used to convert that. It will use CSV file as a parameter, store the headers for separate key arrays and read each row into an array. Then combine key and array to construct a key-value pair format.

// php function to convert csv to json format
function csvToJson($fname) {
    // open csv file
    if (!($fp = fopen($fname, 'r'))) {
        die("Can't open file...");
    //read csv headers
    $key = fgetcsv($fp,"1024",",");
    // parse csv rows into array
    $json = array();
        while ($row = fgetcsv($fp,"1024",",")) {
        $json[] = array_combine($key, $row);
    // release file handle
    // encode array to json
    return json_encode($json);

So the above function fgetcsv($fp,“1024”,”,”) is going to read a row from the CSV file into an array while “1024” parameter is the character length of the CSV row and the last “,” parameter delimits the column. While the json_encode() function will encode the PHP array into a JSON string respectively.



// output

// [{"Id":"1","Name":"Suki Burks","Position":"Developer","Salary":"$114500"
},{"Id":"2","Name":"Fred Zupers","Position":"Technical Author","Salary":"$145000"}
,{"Id":"3","Name":"Gavin Cortez","Position":"Team Leader","Salary":"$235500"}]

So this small PHP function can convert CSV to JSON string, if you want your json file to store separately you can. This is how we can convert any CSVs to JSON formats. Let us know in the comments for further queries.