如何用PHP生成.json文件?
CREATE TABLE Posts
{
id INT PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(200),
url VARCHAR(200)
}
json.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文件。
Egglabs asked 2019-07-13T19:44:54Z
8个解决方案
215 votes
这是一个示例代码:
$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);
?>
Alec Smart answered 2019-07-13T19:45:02Z
30 votes
用这个:
$json_data = json_encode($posts);
file_put_contents('myfile.json', $json_data);
您必须在运行脚本之前创建myfile.json。
RileyManda answered 2019-07-13T19:45:29Z
27 votes
将获取的值插入数组而不是回显。
如果$rows是您的数据,请使用file_put_contents()并将json_encode($rows)插入该文件中。
chelmertz answered 2019-07-13T19:46:01Z
6 votes
使用PHP的json方法创建json,然后使用fwrite将其写入文件。
Quentin answered 2019-07-13T19:46:29Z
6 votes
您可以简单地使用php的json_encode函数并使用文件处理函数(如fopen和fwrite)保存文件。
Sarfraz answered 2019-07-13T19:46:54Z
6 votes
如果您正在提取动态记录,最好有1个php文件创建一个json表示而不是每次都创建一个文件。
my_json.php
$array = array(
'title' => $title,
'url' => $url
);
echo stripslashes(json_encode($array));
然后在脚本中设置文件my_json.php的路径
CyberJunkie answered 2019-07-13T19:47:32Z
6 votes
这里我已经提到了创建json文件的简单语法,并以漂亮的方式在json文件中打印数组值。
$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);
希望它对你有用....
Pasupathi Thangavel answered 2019-07-13T19:48:03Z
5 votes
首先,您需要解码它:
$jsonString = file_get_contents('jsonFile.json');
$data = json_decode($jsonString, true);
然后更改数据:
$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";
}
}
然后重新编码并将其保存回文件中:
$newJsonString = json_encode($data);
file_put_contents('jsonFile.json', $newJsonString);
复制
Darkcoder answered 2019-07-13T19:48:42Z