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

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.

This question is related to php json

The answer is


If you're pulling dynamic records it's better to have 1 php file that creates a json representation and not create a file each time.

my_json.php

$array = array(
    'title' => $title,
    'url' => $url
);

echo stripslashes(json_encode($array)); 

Then in your script set the path to the file my_json.php


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


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.


First, you need to decode it :

$jsonString = file_get_contents('jsonFile.json');
$data = json_decode($jsonString, true);

Then change the data :

$data[0]['activity_name'] = "TENNIS";
// or if you want to change all entries with activity_code "1"
foreach ($data as $key => $entry) {
    if ($entry['activity_code'] == '1') {
        $data[$key]['activity_name'] = "TENNIS";
    }
}

Then re-encode it and save it back in the file:

$newJsonString = json_encode($data);
file_put_contents('jsonFile.json', $newJsonString);

copy


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.


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


Here i have mentioned the simple syntex for create json file and print the array value inside the json file in pretty manner.

$array = array('name' => $name,'id' => $id,'url' => $url);
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($array, JSON_PRETTY_PRINT));   // here it will print the array pretty
fclose($fp);

Hope it will works for you....