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:
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.
0 comments:
Post a Comment