Home > Article > Backend Development > How to Convert Data to JSON Format Using PHP?
How to Generate JSON Data with PHP
To generate JSON data with PHP, one can leverage powerful functions like json_encode(). This function converts data structures, such as arrays, into JSON strings.
Database-Based JSON Generation
Consider the scenario of generating JSON from a database query. Here's a revised example:
<code class="php">$sql = "SELECT * FROM Posts LIMIT 20"; $result = $db->query($sql); $posts = $result->fetch_all(MYSQLI_ASSOC); echo json_encode($posts);</code>
This code connects to a database and executes the query. It then retrieves the results as an array using fetch_all() and passes it to json_encode() to convert it into a JSON string.
Saving JSON to a File
If desired, you can save the JSON data to a file:
<code class="php">file_put_contents('myfile.json', json_encode($posts));</code>
This function writes the JSON string to a file named myfile.json. The resulting file can then be processed as needed.
The above is the detailed content of How to Convert Data to JSON Format Using PHP?. For more information, please follow other related articles on the PHP Chinese website!