PHP – Create JSON file
In this tutorial, we are going to see how to Create JSON file in PHP. Maybe you need JSON to power your graphical visualizations, or you just need to send an HTTP request with a properly formatted JSON. This tutorial explains how to create a properly formatted JSON file.
Suppose we have the following table, and we want the output to be in JSON format.
+--------------+ | Name | +--------------+ | Alex | | Emily | | Bob | | Thomas | | Jean | +--------------+
In the following PHP code, we’ll convert the result of the database query into JSON. The desired result is a simple list of names. This means that the JSON will have a key “name” and an associated value.
[st_adsense]
Create JSON file in PHP:
<?php /*...*/ $sql = "SELECT name FROM users"; $stmt = $conn->prepare($sql); $stmt->execute(); $res = $stmt->get_result(); // DB result $json = "["; //Add open bracket [ at the beginning. $i=0; // Index to manage commas. while ($row = $res->fetch_assoc()) { if ($i == 0) // Run this if the 1st block. { $json .= '{"name" : "'.$row["name"].'" }'; } else { // prefix the JSON with a comma for each iteration. $json .= ', {"name" : "'.$row["name"].'" }'; } $i++; } $json .= "]"; // close the JSON echo $json; ?>
Output:
[{ "name": "Alex" }, { "name": "Emily" }, { "name": "Bob" }, { "name": "Thomas" }, { "name": "Jean" }][st_adsense]