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

1
  • This question is similar to: Returning JSON from PHP to JavaScript?. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Dec 28, 2024 at 19:29

8 Answers 8

293

To generate JSON in PHP, you need only one function, json_encode().

When working with database, you need to get all the rows into array first. Here is a sample code for mysqli

$sql="select * from Posts limit 20"; 
$result = $db->query($sql);
$posts = $result->fetch_all(MYSQLI_ASSOC);

then you can either use this array directly or make it part of another array:

echo json_encode($posts);
// or
$response = json_encode([
    'posts' => $posts,
]);

if you need to save it in a file then just use file_put_contents()

file_put_contents('myfile.json', json_encode($posts));
Sign up to request clarification or add additional context in comments.

6 Comments

I used this code on my project. results.json file works well on local host and fails on remote server. Can you explain why so..
Fwrite could be turned off in your server settings
allthough this is great maybe because I'm using PHP 5 now and it wasn't available at the time this answer was posted but you can get rid of the $result= line and inside your while loop just make the mysql_feth_array($sql)
Please update 1st line to $sql = "select * from Posts limit 20"; , remove mysql_query()
fwrite($fp, json_encode($response,JSON_PRETTY_PRINT)); - uses whitespace to format the JSON. Other constants here
|
73

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.";
?>

Example2: Another example with a json data and error handling.

<?php

// Data stored in an array called posts
$posts = [
    [
        "id" => "01",
        "title" => "Hello",
    ],
    [
        "id" => "02",
        "title" => "Yoyo",
    ],
    [
        "id" => "03",
        "title" => "I like Apples",
    ]
];

// Encode array to JSON with formatting
$json = json_encode($posts, JSON_PRETTY_PRINT);

// Write JSON to file and handle errors
$file = "myfile.json";
if (file_put_contents($file, $json) !== false) {
    echo "Data has been written to $file.";
} else {
    echo "Error occurred while writing to $file.";
}
?>

When JSON_PRETTY_PRINT is passed as the second argument to json_encode(), it tells the function to add whitespace and formatting to the generated JSON string. This makes the resulting JSON structure easier to read and understand when viewing it directly.

Example3: With SQL data from a server:

<?php

// Connect to the database
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";

$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Fetch data from the database
$sql = "SELECT id, name, email FROM users";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    $users = array();
    while ($row = $result->fetch_assoc()) {
        $users[] = $row;
    }

    // Encode SQL data to JSON
    $json = json_encode($users, JSON_PRETTY_PRINT);

    // Write JSON to file
    $file = "users.json";
    if (file_put_contents($file, $json) !== false) {
        echo "Data has been written to $file.";
    } else {
        echo "Error occurred while writing to $file.";
    }
} else {
    echo "No data found.";
}

// Close the database connection
$conn->close();
?>

4 Comments

In fact at the comment date there is no need to create the file before saving the data. Though you still have to create the non-existing subfolders, if any, along the saving path. Here is the official doc for file_put_contents just for convenience.
Yes,programming languages evolve.My post answer was posted in 2017.You should have posted a new answer with an updated way of doing it instead of just downvoted code that worked in 2017
There is no change to the snipped you gave. Just the way file_put_contents works that I mentioned in my initial comment.
Ok,thanks,il make the necessary changes to my answer.Thanks Valentine
32

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.

1 Comment

I see your answer was posted before the most upvoted one. If only you had put some example code, you would have gotten many more votes.
10

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 json_encode($array); 

        

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

2 Comments

When i try to run this using getJason, i get Resource interpreted as Script but transferred with MIME type text/html in console.
@noobcode To fix that, I think you should set a 'Content-Type' header in your 'my_json.php' .
8

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

Comments

7

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

Comments

6

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

Comments

5

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.