How to Convert JSON file into CSV in PHP ?
Last Updated :
13 Apr, 2021
In this article, we are going to see how to convert JSON data into a CSV file using PHP.
JSON (JavaScript Object Notation) is a dictionary-like notation that can be used to structuring data. It is stored with the extension .json, for example – geeksforgeeks.json
On the other hand, CSV (or Comma Separated Value) files represent data in a tabular format, with several rows and columns. An example of a CSV file can be an Excel Spreadsheet. These files have the extension of .csv, for example – geeksforgeeks.csv.
Requirements: XAMPP Server
Structure of JSON:
[{
"data1": "value1",
"data2": "value2",
...,
"data n": "value n"
}]
Example:
[{
"student": "sravan kumar",
"age": 22,
"subject": "java"
}]
Used Methods:
- json_decode() Method: This function is used to decode or convert a JSON object to a PHP object.
Syntax:
json_decode( string, assoc )
Example:
$jsondata = '[{
"student": "sravan kumar",
"age": 22,
"subject": "java"
},
{
"student": "ojaswi",
"age": 21,
"subject": "java"
},
{
"student": "rohith",
"age": 22,
"subject": "dbms"
},
{
"student": "bobby",
"age": 22,
"subject": "sql"
}]';
// Decode the json data and convert it
// into an associative array
$jsonans = json_decode($jsondata, true);
- fopen() Method: It is used to open a file.
Syntax:
fopen( filename, file_mode )
Example:
// File pointer in writable mode
$file_pointer = fopen($csv, 'w');
- fclose() Method: It is used to close the file.
Syntax:
fclose( $file_pointer );
Example:
fclose( $file_pointer );
- fputcsv() Method: It is used to place the data into CSV file.
Syntax:
fputcsv( file, fields )
Example:
fputcsv( $file_pointer, $i );
Steps to Run:
- Open notepad and type the following code in json.php and place it under htdocs folder.
PHP code:
PHP
<?php
$jsondata =
'[
{ "student" : "sravan kumar" , "age" :22, "subject" : "java" },
{ "student" : "ojaswi" , "age" :21, "subject" : "java" },
{ "student" : "rohith" , "age" :22, "subject" : "dbms" },
{ "student" : "bobby" , "age" :22, "subject" : "sql" }]';
$jsonans = json_decode( $jsondata , true);
$csv = 'geeks.csv' ;
$file_pointer = fopen ( $csv , 'w' );
foreach ( $jsonans as $i ){
fputcsv ( $file_pointer , $i );
}
fclose( $file_pointer );
?>
|
Output: Type localhost/json.php in your browser. You can see the CSV file is created with the file name as geeks.csv
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...