//設定連線編碼規則,不懂上google找
mysqli_query($conn,'SET NAMES 'utf8'');
//取出資料
$results = mysqli_query($conn,'SELECT id,type,title FROM news');
//Josn字串
$json = '';
//因為是範例,所以自行控制迴圈
$i=0;
while($row = mysqli_fetch_assoc($results))
{
$i++;
$json .= json_encode($row);
//資料表中只放三筆資料,所以在第三筆時不需要在尾巴加上 ",",記得,最後一筆資料不用加上","
if ($i<3)
{
$json .= ",";
}
}
//將資料包進陣列中
$json = '{"query":[ '.$json.']}';?>
<!doctype html public "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" xml:lang="zh-tw" lang="zh-tw" >
<head>
<title>Json範例</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="-1" />
<meta http-equiv="Cache-Control" content="no-cache" />
<meta name="generator" content="mamba" />
</head>
<body>
<script type="text/javascript">
var json = <?php echo $json?>;
alert('I have ' +json.query.length + ' object.');
alert('type='+json.query[1].type+'rntitle'+json.query[1].title);
//上一篇簡介中使用過
</script>
還原Json<br>
<?php
//將字串解碼
$s_JSON_Decoded = json_decode($json,true);
//取回資料
foreach ($s_JSON_Decoded as $row)
{
foreach ($row as $rowa)
{
echo $rowa['title']."<br>";
}
}
?>
</body>
</html>
經過簡單的演練後
相信大家對JSON這玩意有更深一層的瞭解
當然JSON的應用不只是範例中那麼簡單
有興趣一起研究吧







