How to generate .json file with PHP? How to generate .json file with PHP? php php

How to generate .json file with PHP?


Here is a sample code:

<?php $sql="select * from Posts limit 20"; $response = array();$posts = array();$result=mysql_query($sql);while($row=mysql_fetch_array($result)) {   $title=$row['title'];   $url=$row['url'];   $posts[] = array('title'=> $title, 'url'=> $url);} $response['posts'] = $posts;$fp = fopen('results.json', 'w');fwrite($fp, json_encode($response));fclose($fp);?> 


Use this:

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

You have to create the myfile.json before you run the script.

(NB:This is not compulsory as suggested by Valentine in the comments below:)

Here is a working Example:

<?php   // data strored in an array called cars$cars = Array (    "0" => Array (        "id" => "01",        "name" => "BMW",    ),    "1" => Array (        "id" => "02",        "name" => "Volvo",    ),    "2" => Array (        "id" => "03",        "name" => "Mercedes",    ));// encode array to json$json = json_encode($cars);$bytes = file_put_contents("myfile.json", $json); //generate json fileecho "Here is the myfile data $bytes.";?>


Insert your fetched values into an array instead of echoing.

Use file_put_contents() and insert json_encode($rows) into that file, if $rows is your data.