How to convert json file into csv in php?

In this article, we are going to see how to convert JSON data into a CSV file using PHP.

1. Code:

<?php
// Student JSON data
$jsondata = 
  '[
   {"student":"Soltuts 1","age":22,"subject":"java"},
   {"student":"Soltuts 2","age":21,"subject":"java"},
   {"student":"Soltuts 3","age":22,"subject":"dbms"},
   {"student":"Soltuts 4","age":22,"subject":"sql"}]';
   
// Decode json data and convert it
// into an associative array
$jsonans = json_decode($jsondata, true);
 
// CSV file name => D:\soltuts.csv
$csv = 'D:\soltuts.csv';
   
// File pointer in writable mode
$file_pointer = fopen($csv, 'w');
   
// Traverse through the associative
// array using for each loop
foreach($jsonans as $i){
    // Write the data to the CSV file
    fputcsv($file_pointer, $i);
}
// Close the file pointer.
fclose($file_pointer);
?>

2. Example:

Input:

$jsondata = 
  '[
   {"student":"Soltuts 1","age":22,"subject":"java"},
   {"student":"Soltuts 2","age":21,"subject":"java"},
   {"student":"Soltuts 3","age":22,"subject":"dbms"},
   {"student":"Soltuts 4","age":22,"subject":"sql"}]';
   

Output:

"Soltuts 1",22,java
"Soltuts 2",21,java
"Soltuts 3",22,dbms
"Soltuts 4",22,sql