-
-
Save PurinWang/932ed474e149041ebaee04988c0a11d2 to your computer and use it in GitHub Desktop.
PTX (公共運輸整合資訊流通服務平臺) 的 php 查詢範例
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
# PTX (公共運輸整合資訊流通服務平臺) 的 php 查詢範例 | |
# 網址: https://ptx.transportdata.tw/PTX | |
# 本程式不需要任何外加套件; 但關於 「如何保護私密資訊」, 請見 | |
# http://phpsec.org/projects/guide/3.html | |
# 的 "PHP Cookbook" 那一段 | |
# 如果省略上面步驟, 那就必須把下面的註解打開, | |
# 在程式碼裡填上 id 跟 key (限測試用; 請勿使用真的 id 跟 key!) | |
#$_SERVER['PTX_ID'] = 'FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF'; | |
#$_SERVER['PTX_KEY'] = 'FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF'; | |
//PTX規定日期需要雙兩位數的format | |
$time_string = gmdate('D, d M Y H:i:s') . ' GMT'; | |
$signature = base64_encode(hash_hmac("sha1", "x-date: $time_string", $_SERVER['PTX_KEY'], true)); | |
$opts = [ | |
"http" => [ | |
"method" => "GET", | |
"header" => | |
'Authorization:hmac username="' . $_SERVER['PTX_ID'] . '", algorithm="hmac-sha1", headers="x-date", signature="' . "$signature\"\n" . | |
"x-date:$time_string\n" | |
//"Accept-Encoding: gzip, deflate\n",(不須加入這個編碼會導致沒解壓縮造成亂碼) | |
] | |
]; | |
$ret = file_get_contents( | |
'http://ptx.transportdata.tw/MOTC/APIs/v2/Rail/TRA/Station?$top=5&$format=JSON', false, stream_context_create($opts) | |
); | |
echo $ret; | |
?> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment