第一種情形---JSON直接寫在PHP程式碼內
<html>
<head>
<title>Online PHP Script Execution</title>
</head>
<body>
<?php
$json = '[
{
"source":"symbols/2/2.png",
"ypos":133,
"template":"8B82CA47-41D2-D624-D6A2-37177CD82F28",
"rotation":0,
"type":"MyImage",
"width":252,
"depth":5,
"height":159,
"xpos":581
},
{
"source":"symbols/2/2.png",
"ypos":175,
"template":"8B82CA47-41D2-D624-D6A2-37177CD82F28",
"rotation":0,
"type":"MyImage",
"width":258,
"depth":3,
"height":163,
"xpos":214
},
{
"color":"0",
"ypos":468.38,
"fontSize":28,
"xpos":156.95,
"rotation":0,
"type":"MyTextArea",
"width":268.05,
"depth":7,
"height":244.62,
"fontFamily":"Verdana Bold",
"template":"8B82CA47-41D2-D624-D6A2-37177CD82F28"
}
]';
$result = json_decode($json);
foreach($result as $key => $value) {
if($value) {
//how to use json array to insert data in Database
echo "$value->source"." $value->ypos"." $value->template<br>";
}
}
?>
</body>
</html>
第二種情形---JSON是在別的網站的網頁上
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Online PHP Script Execution</title>
</head>
<body>
<?php
$handle = fopen("http://data.kaohsiung.gov.tw/Opendata/DownLoad.aspx?Type=2&CaseNo1=AV&CaseNo2=1&FileType=1&Lang=C&FolderType=","rb");
content = "";
while (!feof($handle)) {
$content .= fread($handle, 10000);
}
fclose($handle);
$content = json_decode($content);
foreach ($content as $key => $value) {
echo "$value->Name<br>";
}
?>
</body>
</html>
第三種情形---JSON是放在自己網站裡的檔案
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Online PHP Script Execution</title>
</head>
<body>
<?php
$handle = fopen("./myfile.json","rb");
$content = "";
while (!feof($handle)) {
$content .= fread($handle, 10000);
}
fclose($handle);
$content = json_decode($content);
foreach ($content as $key => $value) {
echo "$value->Name<br>";
}
?>
</body>
</html>
第四種情形---JSON是由MySQL查詢資料組成
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Online PHP Script Execution</title>
</head>
<body>
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "KHtravel";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
mysqli_query($conn,"SET NAMES utf8");
$sql = "SELECT id, name FROM KHtravel";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$myarray[] = $row;
}
} else {
echo "0 results";
}
$myarray = array('KHtravel' => $myarray);
echo json_encode($myarray,JSON_UNESCAPED_UNICODE);
mysqli_close($conn);
?>
</body>
</html>