<?php session_start(); require("data_go_th_mytoken.php"); ?><!DOCTYPE html><html lang="th"><head>
<title>นำข้อมูลจาก data.go.th ใช้ผ่าน api และ php</title>
<meta charset="utf-8" /></head><body>
<div id="explain" style="width:728px;margin-right:auto;margin-left:auto;display:table;">
ตัวอย่าง โค้ดสำหรับอ่านชุดข้อมูลไปแสดงบนเว็บเพจ เป็น ข้อมูลทรัพยากร : สมาคมด้านการท่องเที่ยวของจังหวัด - ลำปาง
จากศูนย์กลางข้อมูลเปิดภาครัฐ โดยอ้างอิงที่อยู่ชุดข้อมูลแบบออนไลน์ และมีกุญแจเอพีไอที่ระบบมอบให้มา
ตามคำร้องขอของสมาชิก (api-key) เพื่ออนุญาตให้ใช้ข้อมูลได้ โดยเขียนโค้ดด้วยภาษาพีเอชพี ที่ใช้คำสั่ง curl
โหลดข้อมูลผ่านตำแหน่งยูอาร์แอลออกไปใช้ ได้ข้อมูลแบบ json แล้ว decode เป็น object นำไปแยกลงตัวแปร
บนจาวาสคริปต์ ในรูปแบบ csv โดยใช้ split แยกข้อมูลเป็น อาร์เรย์ เพื่ออ่านแต่ละ field และ record
วนลูปด้วย foreach และ for แล้วใช้คำสั่ง document.write แสดงข้อมูลแบบอาร์เรย์ลงตารางแบบเอชทีเอ็มแอล
</div>
<table style="width:728px;margin-right:auto;margin-left:auto;border:1px solid black;">
<tr><td>ลำดับ</td><td>ชื่อสมาคม/ชมรม</td><td>ชื่อนายก/ประธาน</td><td>เบอร์โทร</td></tr>
<script>
<?php
$api_key = array('api-key:'. base64_decode($_SESSION["token"]));
$url_long = "https://opend.data.go.th/get-ckan/datastore_search?resource_id=99326be4-8f67-4d2a-be58-5e5317a03db4&limit=50";
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url_long,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTPHEADER => $api_key
));
$response = curl_exec($curl);
curl_close($curl);
$obj = json_decode($response);
echo "var data = '\\\r\n";
foreach($obj->{"result"}->{"records"} as $o){
foreach($o as $v){
$v = str_replace("\n"," ",$v);
echo "$v,";
}
echo "\\" . "\r\n";
}
echo "';";
?>
var array_data = data.split(",");
var seq = 1; var fld;
for(rows=1;rows<=12;rows++){
fld = rows * 4;
document.write('<tr><td>'+ (seq++) + '</td><td>' + array_data[fld - 3] + '</td>\
<td>' + array_data[fld - 2] + '</td><td>' + array_data[fld - 1] + '</td></tr>');
}
</script>
</table>
<div style="margin-left:auto;margin-right:auto;display:table;"><a href="index.php" title="back">back</a></div>
</body></html>
จำนวน : 53 บรรทัด