PHP: Convert JSON to CSV.

This is a tutorial on how to convert JSON data into CSV  file using PHP. Essentially, we will decode the JSON data before writing it to a CSV file.

For this tutorial, we will be using the following JSON data:


Obviously, you can swap in whatever JSON source you are using.

Let’s take a look at a simple example:


//An example JSON string.
$jsonString = '[{"name":"Wayne","age":28},{"name":"John","age":21},{"name":"Sara","age":24}]';

//Decode the JSON and convert it into an associative array.
$jsonDecoded = json_decode($jsonString, true);

//Give our CSV file a name.
$csvFileName = 'example.csv';

//Open file pointer.
$fp = fopen($csvFileName, 'w');

//Loop through the associative array.
foreach($jsonDecoded as $row){
    //Write the row to the CSV file.
    fputcsv($fp, $row);

//Finally, close the file pointer.

A break-down of the code snippet above:

  1. We created a simple JSON string for example purposes.
  2. We decoded the JSON string into an associative PHP array.
  3. We gave our CSV file a name. In this case, it is example.csv
  4. We opened a writable file pointer using the fopen function. This file pointer allows us to write data to a particular file.
  5. We loop through our associative array, which contains our decoded JSON data.
  6. Inside the foreach loop, we write to our CSV file using the function fputcsv.
  7. At the end, we close our file pointer.

If you run the code, you should find that a file called example.csv has been created and that it can be opened in applications such as Excel and Libre Office Calc.

PS: If you are wanting to force the CSV file to download, then you can take a look at this tutorial on creating CSV files with PHP.

Related: Converting CSV files into JSON.