Home > Backend Development > PHP Tutorial > How to Output JSON Data from MySQL Database Using PHP\'s json_encode()?

How to Output JSON Data from MySQL Database Using PHP\'s json_encode()?

Susan Sarandon
Release: 2024-10-19 22:09:02
Original
627 people have browsed it

How to Output JSON Data from MySQL Database Using PHP's json_encode()?

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

Generating JSON with json_encode():

<code class="php">$response = json_encode($posts);

// Output the JSON data
echo $response;</code>
Copy after login

If you need to save the JSON data to a file, you can use:

<code class="php">file_put_contents('results.json', $response);</code>
Copy after login

Explanation:

  • The json_encode() function converts the PHP array ($posts) into a JSON string.
  • The file_put_contents() function writes the JSON string to a file named "results.json".

Benefits of Using json_encode():

  • Simplifies the generation of JSON data from PHP arrays.
  • Supports proper JSON formatting and escaping.
  • Allows for flexible customization of the JSON structure.

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!

source:php
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 Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template