<!DOCTYPE html><html lang="th"><head>
<title>นำแฟ้ม .csv จาก data.go.th ไปฝากกับ thaiabc แล้วอ่านด้วย curl</title>
<meta charset="utf-8" /></head><body>
<div id="explain" style="width:728px;margin-right:auto;margin-left:auto;display:table;">
ตัวอย่าง โค้ดสำหรับอ่านชุดข้อมูล ที่แหล่งข้อมูลต้นทาง เปิดให้ดาวน์โหลดแฟ้มแบบ .csv
ในกรณีนี้ต้องการนำไปแสดงบนเว็บเพจ เป็น ข้อมูลทรัพยากร : สมาคมด้านการท่องเที่ยวของจังหวัด - ลำปาง
จากศูนย์กลางข้อมูลเปิดภาครัฐ โดยอ้างอิงที่อยู่ชุดข้อมูลแบบออนไลน์ ที่ได้ดาวน์โหลดจากเครื่องบริการของรัฐ
ไปวางบนเครื่องบริการตัวที่สองแล้วเขียนโค้ดบนเครื่องบริการตัวที่สาม แบบนี้ไม่ต้องใช้ api-key
เขียนโค้ดด้วยภาษาพีเอชพี และใช้ฟังก์ชัน curl โหลดข้อมูลผ่านตำแหน่งยูอาร์แอล
ของเครื่องบริการตัวที่สองที่เก็บข้อมูลออกไปใช้ ได้ข้อมูลแบบ csv แล้วนำไปวางลงตัวแปร บนจาวาสคริปต์
ในรูปแบบ csv ที่จัดรูปแบบเพียงเล็กน้อย เพื่ออ่านหลังการ split แยกแต่ละ field และ record วนลูปด้วย foreach
แล้วใช้คำสั่ง document.write แสดงข้อมูลแบบอาร์เรย์ลงตารางแบบเอชทีเอ็มแอล
</div>
<table style="width:728px;margin-right:auto;margin-left:auto;border:1px solid black;">
<tr style="background-color:#dddddd;"><td>ลำดับ</td><td>ชื่อสมาคม</td><td>จังหวัด</td><td>ปี</td></tr>
<script>
<?php
$url_long = "http://www.thaiabc.com/travelassoc/lp67_22_009-.csv";
$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 => ""
));
$response = curl_exec($curl);
curl_close($curl);
echo "var data = '\\\r\n";
$response = str_replace("\r\n",",\\"."\r\n",$response);
echo $response . "';";
?>
var array_data = data.split(",");
var seq = 1; var fld;
for(rows=2;rows<=13;rows++){
fld = rows * 3;
document.write('<tr><td>'+ (seq++) + '</td><td>' + array_data[fld - 1] + '</td>\
<td>' + array_data[fld - 2] + '</td><td>' + array_data[fld - 3] + '</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>
จำนวน : 47 บรรทัด