How to import JSON data into CSV file with PHP and MySQL?
During the development process, we often encounter situations where we need to convert data from one format to another. For example, sometimes we need to import JSON data into a CSV file. This article will introduce how to import JSON data into a CSV file using PHP and MySQL.
First, we need to prepare a JSON data file. Suppose we have a file named "data.json" which contains the following JSON data:
[ { "id": 1, "name": "John", "age": 25 }, { "id": 2, "name": "Jane", "age": 30 }, { "id": 3, "name": "Mike", "age": 35 } ]
Next, we need to write PHP code to import the JSON data and convert it to CSV format. We can use PHP's built-injson_decode()
function to decode JSON data into a PHP array. We will then use thefputcsv()
function to write the data to the CSV file.
Below is the complete PHP code example:
In the above example, we first read the contents of the JSON file using thefile_get_contents()
function and usejson_decode()
Function decodes it into a PHP array. Then, we create a new CSV file and turn on write mode. We use thefputcsv()
function to write the header of the CSV file to the file, and then useforeach
to loop through the data array and write each row of data to the CSV file. Finally, we close the CSV file.
To run the above code, you need to create a file named "data.json" in the same directory as the PHP file and copy the above given JSON data into the file. Then, run the PHP file and it will generate a CSV file named "output.csv".
Summary:
This article introduces how to use PHP and MySQL to import JSON data into a CSV file. We can easily achieve this conversion by using thejson_decode()
function to decode the JSON data into a PHP array and thefputcsv()
function to write the data to a CSV file. This is a very useful technique that can help us with data format conversion during the development process. Hope this article helps you!
The above is the detailed content of How to import JSON data into CSV file with PHP and MySQL?. For more information, please follow other related articles on the PHP Chinese website!