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.
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.