简体   繁体   中英

How to generate JSON data 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.

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

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

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

        

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

您可以简单地使用 php 的json_encode函数并使用fopenfwrite等文件处理函数保存文件。

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

使用 PHP 的json 方法创建 json,然后使用fwrite将其写入文件。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM