一尘不染

如何用PHP生成.json文件?

php

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文件。


阅读 926

收藏
2020-05-29

共1个答案

一尘不染

这是一个示例代码:

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


?>
2020-05-29