tags:

views:

604

answers:

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

A: 

Use PHP's json methods to create the json then write it to a file with fwrite.

David Dorward
+1  A: 

You can simply use json_encode function of php and save file with file handling functions such as fopen and fwrite.

Sarfraz
A: 

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.

chelmertz
+1  A: 

Here is a sample code:

<?php 
$sql=mysql_query("select * from Posts limit 20"); 

$response = array();
$posts = array();
while($row=mysql_fetch_array($sql)) 
{ 
$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);


?> Done!
Alec Smart
Thank you.. It is perfect
Srinivas Tamada