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:
[{"name":"Wayne","age":28},{"name":"John","age":21},{"name":"Sara","age":24}]
Obviously, you can swap in whatever JSON source you are using.
Let’s take a look at a simple example:
<?php //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. fclose($fp);
A break-down of the code snippet above:
- We created a simple JSON string for example purposes.
- We decoded the JSON string into an associative PHP array.
- We gave our CSV file a name. In this case, it is example.csv
- We opened a writable file pointer using the fopen function. This file pointer allows us to write data to a particular file.
- We loop through our associative array, which contains our decoded JSON data.
- Inside the foreach loop, we write to our CSV file using the function fputcsv.
- 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.