Convert JSON to CSV using PHP (JSON Keys as Column Headers)

On 11/08/2017

Hi! Here's how to convert json to csv in php by using json keys as column headers for csv file. Even though json format is immensely popular for data exchange over web, there are times you may need to work with csv data and have to convert json to csv. Being a modern language, php doesn't have trouble handling both data formats but unfortunately there's no one step solution to convert json to csv using php. But don't worry! I have created a simple php script for json to csv conversion.

In case you don't know, json stores data as 'key:value' pairs. And the function I have created will take valid json keys and use it as column headers for the csv file during conversion.

I have already discussed about converting csv to json in php and below we'll see about converting json to csv in php.

But keep in mind there are so many things can go wrong during this conversion so you need to do proper error handling in the script.

How to Convert JSON to CSV in PHP?

We'll need a sample json file for converting to csv. So let's take this below one as example.

data.json

[
    {
        "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"
    }
]

PHP Function to Convert JSON to CSV:

Here's the php conversion function. The function has two parameters 1. $jfilename - which is the path of the json file to be converted and 2. $cfilename - and this is the csv filename where the converted data will be stored.

The script reads the json file contents, decodes json string into an array, remove the keys from the array and write it as column headers and parse through the array one by one and write down the data into csv file.

<?php
function jsonToCSV($jfilename, $cfilename)
{
    if (($json = file_get_contents($jfilename)) == false)
        die('Error reading json file...');
    $data = json_decode($json, true);
    $fp = fopen($cfilename, 'w');
    $header = false;
    foreach ($data as $row)
    {
        if (empty($header))
        {
            $header = array_keys($row);
            fputcsv($fp, $header);
            $header = array_flip($header);
        }
        fputcsv($fp, array_merge($header, $row));
    }
    fclose($fp);
    return;
}
?>
  • The function file_get_contents($jfilename) returns the content of the json file.
  • Next json_decode($json, true) decodes the json string into an associative array.
  • The function array_keys($row) will return the keys from an associative array.
  • And array_merge($header, $row) will keep the order of elements according to csv column headers.

Function Usage:

To convert json to csv file,

$json_filename = 'data.json';
$csv_filename = 'data.csv';
jsonToCSV($json_filename, $csv_filename);
echo 'Successfully converted json to csv file. <a href="' . $csv_filename . '" target="_blank">Click here to open it.</a>';

If everything goes right, this will convert the given json file into csv and display the csv file link like this on browser,

php json to csv conversion

Clicking on the link will open the csv file in Microsoft Excel.

Here's the complete script for your reference.

<?php
function jsonToCSV($jfilename, $cfilename)
{
    if (($json = file_get_contents($jfilename)) == false)
        die('Error reading json file...');
    $data = json_decode($json, true);
    $fp = fopen($cfilename, 'w');
    $header = false;
    foreach ($data as $row)
    {
        if (empty($header))
        {
            $header = array_keys($row);
            fputcsv($fp, $header);
            $header = array_flip($header);
        }
        fputcsv($fp, array_merge($header, $row));
    }
    fclose($fp);
    return;
}

$json_filename = 'data.json';
$csv_filename = 'data.csv';

jsonToCSV($json_filename, $csv_filename);
echo 'Successfully converted json to csv file. <a href="' . $csv_filename . '" target="_blank">Click here to open it.</a>';
?>

Related Read: How to Convert CSV to JSON using PHP

That explains about converting csv to json in php. I hope you find this php script useful. Meet you in another interesting tutorial.

1 comment:

Contact Form

Name

Email *

Message *