PHP JSON To CSV File (Simple Examples)

Welcome to a tutorial on how to write JSON data to a CSV file in PHP. So you are working on a project that maybe received JSON data from an API and need to write that to a CSV file?

It is a 2 steps process to do “JSON to CSV” in PHP.

  • Convert the JSON data to an array first.
  • Then write the array to the CSV file.

Just how do we do that exactly? Read on for the examples!

 

 

TABLE OF CONTENTS

 

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

 

EXAMPLE CODE DOWNLOAD

Source code on GitHub Gist

Just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

SORRY FOR THE ADS...

But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.

Buy Me A Coffee Code Boxx eBooks

 

 

PHP JSON TO CSV

All right, let us now get into the examples of how to convert JSON data and write it to a CSV file.

 

EXAMPLE 1) NESTED JSON ARRAY

1a-data.json
[["Joe Doe","joe@doe.com"],["Jon Doe","jon@doe.com"],["Joy Doe","joy@doe.com"]]
1b-nested-array.php
<?php
// (A) JSON DATA TO ARRAY
$data = file_get_contents("1a-data.json");
$data = json_decode($data);
print_r($data);
 
// (B) WRITE TO CSV
$handle = fopen("demoA.csv", "w");
if ($handle === false) { exit("Error creating CSV file"); }
foreach ($data as $row) { fputcsv($handle, $row); }
fclose($handle);
echo "OK";

For those who are lost, $data is a nested array in the format of [[NAME, EMAIL], [NAME, EMAIL], ...]. Since this is already “nicely formatted”, all we have to do is loop through the entries and write to the CSV file.

 

 

EXAMPLE 2) FLAT ARRAY

2a-data.json
["Joe Doe","joe@doe.com","Jon Doe","jon@doe.com","Joy Doe","joy@doe.com"]
2b-flat-array.php
<?php
// (A) JSON DATA TO ARRAY
$data = file_get_contents("2a-data.json");
$data = json_decode($data);
print_r($data);
 
// (B) WRITE TO CSV
$handle = fopen("demoB.csv", "w");
if ($handle === false) { exit("Error creating CSV file"); }
$i = 0; $j = [];
foreach ($data as $row) {
  $j[] = $row; $i++;
  if ($i==2) {
    fputcsv($handle, $j);
    $i = 0; $j = [];
  }
}
fclose($handle);
echo "OK";

Now, $data in this example is now a flat array in the format of [NAME, EMAIL, NAME, EMAIL, ...]. Yep, since someone did not “nicely format” the data, we have to do it manually. What this example does –

  • Loop through $data, collect the current value into $j and increment $i.
  • When $i==2, we write $j as a row into the CSV file.
  • Rinse-and-repeat until there are no more entires.

 

 

EXAMPLE 3) ASSOCIATIVE ARRAY

3a-data.json
{"NAME":["Joe Doe","Jon Doe","Joy Doe"],"EMAIL":["joe@doe.com","jon@doe.com","joy@doe.com"]}
3b-assoc-array.php
<?php
// (A) JSON DATA TO ARRAY
$data = file_get_contents("3a-data.json");
$data = json_decode($data, true);
print_r($data);
 
// (B) EXTRACT SOME DATA
$keys = array_keys($data);
$entries = count($data[$keys[0]]);
 
// (C) WRITE TO CSV
// (C1) OPEN FILE
$handle = fopen("demoC.csv", "w");
if ($handle === false) { exit("Error creating CSV file"); }
 
// (C2) FIRST ROW - HEADERS
fputcsv($handle, $keys);
 
// (C3) OTHER ROWS - VALUES
for ($i=0; $i<$entries; $i++) {
  $row = [];
  foreach ($keys as $k) { $row[] = $data[$k][$i]; }
  fputcsv($handle, $row);
}
 
// (C4) DONE
fclose($handle);
echo "OK";

In this example, $data is a little funky, in the format of ["NAME": ARRAY OF NAMES, "EMAIL": ARRAY OF EMAILS]. A little more challenging, but trace through and it should explain itself:

  • Extract the keys of $data and use them as the first row of the CSV file.
  • Loop through the rest of the entries and append to the CSV accordingly.

 

 

EXAMPLE 4) MORE ASSOCIATIVE ARRAY

4a-data.json
[{"NAME":"Joe Doe","EMAIL":"joe@doe.com"},{"NAME":"Jon Doe","EMAIL":"jon@doe.com"},{"NAME":"Joy Doe","EMAIL":"joy@doe.com"}]
4b-assoc-array.php
<?php
// (A) JSON DATA TO ARRAY
$data = file_get_contents("4a-data.json");
$data = json_decode($data, true);
print_r($data);
 
// (B) EXTRACT KEYS
$keys = array_keys($data[0]);

// (C) WRITE TO CSV
// (C1) OPEN FILE
$handle = fopen("demoD.csv", "w");
if ($handle === false) { exit("Error creating CSV file"); }
 
// (C2) FIRST ROW - HEADERS
fputcsv($handle, $keys);
 
// (C3) OTHER ROWS - VALUES
foreach ($data as $row) {
  fputcsv($handle, array_values($row));
}

// (C4) DONE
fclose($handle);
echo "OK";

Finally, $data for this one is in the format of [["EMAIL":EMAIL, "NAME":NAME], ["EMAIL":EMAIL, "NAME":NAME], ...]. A lot easier to work with than the previous example.

  • Extract the array keys from $data[0], write to the first row of the CSV file.
  • Loop through $data, extract the values only and write to the CSV file.

The end!

 

 

EXTRAS

That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.

 

LINKS & REFERENCES

 

THE END

Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!