How to import JSON data into CSV file with PHP and MySQL?

WBOY
Release: 2023-07-13 06:16:02
Original
805 people have browsed it

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 } ]
Copy after login

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:

Copy after login

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 useforeachto 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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!