CREATE TABLE Posts
{
id INT PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(200),
url VARCHAR(200)
}
json.php代码
<?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 ']}';
?>
我必须生成results.json
文件。
发布于 2010-03-18 14:45:29
下面是一个示例代码:
<?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);
?>
发布于 2017-01-28 22:02:52
使用以下命令:
$json_data = json_encode($posts);
file_put_contents('myfile.json', $json_data);
你可以在运行script.But之前创建myfile.json,这不是必须的。
下面是一个有效的示例:
<?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.";
?>
发布于 2010-03-18 14:44:34
将获取的值插入数组中,而不是回显。
使用file_put_contents()
并将json_encode($rows)
插入到该文件中(如果$rows
是您的数据)。
https://stackoverflow.com/questions/2467945
复制相似问题