How to generate JSON data with PHP?

To generate JSON in PHP, you need only one function, json_encode().

When working with database, you need to get all the rows into array first. Here is a sample code for mysqli

$sql="select * from Posts limit 20"; 
$result = $db->query($sql);
$posts = $result->fetch_all(MYSQLI_ASSOC);

then you can either use this array directly or make it part of another array:

echo json_encode($posts);
// or
$response = json_encode([
    'posts' => $posts,
]);

if you need to save it in a file then just use file_put_contents()

file_put_contents('myfile.json', json_encode($posts));

Leave a Comment