How to generate JSON data with PHP?

json, php

Solution

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));

Problem

``` CREATE TABLE Posts { id INT PRIMARY KEY AUTO_INCREMENT, title VARCHAR(200), url VARCHAR(200) } ``` json.php code ``` <?php $sql=mysql_query("select * from Posts limit 20"); echo '{"posts": ['; while($row=mysql_fetch_array($sql)) { $title=$row['title']; $url=$row['url']; echo ' { "title":"'.$title.'", "url":"'.$url.'" },'; } echo ']}'; ?> ``` I have to generate `results.json` file.

Original source

Related problems