Thursday, 9 August 2018

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:
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.

0 comments:

Post a Comment