[轉貼] php 台灣銀行的匯率JSON
蠻不錯的分享 記錄下來 🙂
資料來源: http://blog.asper.tw/2015/05/json.html
$site = "http://rate.bot.com.tw"; $csvIndex = array( 'currency'=>0, 'buyCash'=>2, 'buySpot'=>3, 'sellCash'=>12, 'sellSpot'=>13 ); //get csv link $page = "/Pages/Static/UIP003.zh-TW.htm"; $html = file_get_contents($site.$page); $aPos = strpos($html, '<a>', $hrefPos); $link = substr($html, $hrefPos+6, $endPos-$hrefPos-6); $link = htmlspecialchars_decode($link); $updateTime = strtotime(substr($link, strpos($link, '&date=')+6 )); //open taiwan bank rate csv $fp = fopen($site.$link, "r"); $row = 0; $currencyRates = array(); while( ($data = fgetcsv($fp, 1000, ',')) !== FALSE ){ $row++; if($row == 1){ continue; } //skip title row foreach($csvIndex as $name=>$index){ $$name = trim($data[$index]); } $currencyRates[ $currency ] = compact('buyCash', 'buySpot', 'sellCash', 'sellSpot'); } fclose($fp); //save to json cache $data = array( 'createTime' => time(), 'updateTime' => $updateTime, 'rates' => $currencyRates ); echo json_encode( $data );