How to generate .json file with PHP?

PhpJson

Php Problem Overview


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.

Php Solutions


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

 
?> 

Solution 2 - Php

Use this:

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

> You can create the myfile.json before you run the script.But its not compulsory if you have full sudo privileges(read/write permissions(For of you on Mac).

Here is a working Example:

<?php 
  
// data stored in an array called posts
$posts = Array (
    "0" => Array (
        "id" => "01",
        "title" => "Hello",
    ),
    "1" => Array (
        "id" => "02",
        "title" => "Yoyo",
    ),
    "2" => Array (
        "id" => "03",
        "title" => "I like Apples",
    )
);
// encode array to json
$json = json_encode($posts);
$bytes = file_put_contents("myfile.json", $json); //generate json file
echo "Here is the myfile data $bytes.";
?>

Solution 3 - Php

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.

Solution 4 - Php

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

Solution 5 - Php

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

Solution 6 - Php

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

Solution 7 - Php

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

Solution 8 - Php

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEgglabsView Question on Stackoverflow
Solution 1 - PhpAlec SmartView Answer on Stackoverflow
Solution 2 - PhpRileyMandaView Answer on Stackoverflow
Solution 3 - PhpchelmertzView Answer on Stackoverflow
Solution 4 - PhpPasupathi ThangavelView Answer on Stackoverflow
Solution 5 - PhpCyberJunkieView Answer on Stackoverflow
Solution 6 - PhpQuentinView Answer on Stackoverflow
Solution 7 - PhpSarfrazView Answer on Stackoverflow
Solution 8 - PhpDarkcoderView Answer on Stackoverflow