How to Generate JSON Data in PHP Using json_encode()
To generate JSON data from a MySQL database, you can utilize the json_encode() function in PHP. Here's how:
Fetching Database Data into an Array:
<code class="php">$sql = "SELECT * FROM Posts LIMIT 20"; $result = $db->query($sql); $posts = $result->fetch_all(MYSQLI_ASSOC);</code>
Generating JSON with json_encode():
<code class="php">$response = json_encode($posts); // Output the JSON data echo $response;</code>
If you need to save the JSON data to a file, you can use:
<code class="php">file_put_contents('results.json', $response);</code>
Explanation:
Benefits of Using json_encode():
The above is the detailed content of How to Output JSON Data from MySQL Database Using PHP\'s json_encode()?. For more information, please follow other related articles on the PHP Chinese website!