Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate .json file with PHP?

Tags:

json

php

People also ask

Can PHP write to JSON file?

Using PHP scripting we can store a form value in array format. After that will convert the array into JSON data using json_encode() predefined function. Then at last we can move the data to JSON format file.

Can PHP return JSON?

You can simply use the json_encode() function to return JSON response from a PHP script. Also, if you're passing JSON data to a JavaScript program, make sure set the Content-Type header.

What is JSON file in PHP?

What is JSON? JSON stands for JavaScript Object Notation, and is a syntax for storing and exchanging data. Since the JSON format is a text-based format, it can easily be sent to and from a server, and used as a data format by any programming language.


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 can create the myfile.json before you run the script.But its not compulsory.

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 file
echo "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.


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


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


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


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