金山詞霸(ICIBA)提供開放 API 可查詢指定日期的「每日一句」英文語錄。本文示範如何用 PHP 隨機產生日期並呼叫 API 獲取內容,適用於網站每日金句展示、英語學習工具開發等場景。
https://open.iciba.com/dsapi/date=YYYY-MM-DD(可選,預設為今日)content(英文)、note(中文翻譯)、picture(配圖 URL)等欄位<?php
header('Content-Type: text/html; charset=utf-8');
// 1. 隨機產生日期範圍:2012 年至今年
$startYear = 2012;
$endYear = (int)date('Y');
$endMonth = (int)date('m');
$endDay = (int)date('d');
$randYear = mt_rand($startYear, $endYear);
// 注意:若隨機到今年,月份/日期不得超過今日
$randMonth = ($randYear === $endYear) ? mt_rand(1, $endMonth) : mt_rand(1, 12);
$randDay = ($randYear === $endYear && $randMonth === $endMonth)
? mt_rand(1, $endDay)
: mt_rand(1, cal_days_in_month(CAL_GREGORIAN, $randMonth, $randYear));
$date = sprintf('%04d-%02d-%02d', $randYear, $randMonth, $randDay);
// 2. 呼叫 API
$url = 'https://open.iciba.com/dsapi/?date=' . $date;
$json = @file_get_contents($url);
if ($json === false) {
die('API 請求失敗,請檢查網路或 allow_url_fopen 設定');
}
$data = json_decode($json, true);
if (json_last_error() !== JSON_ERROR_NONE) {
die('JSON 解析錯誤:' . json_last_error_msg());
}
// 3. 輸出結果
echo "<h3>金山詞霸每日一句 ($date)</h3>";
echo "<p><strong>英文</strong>: {$data['content']}</p>";
echo "<p><strong>中文</strong>: {$data['note']}</p>";
if (!empty($data['picture'])) {
echo "<p><img src='{$data['picture']}' alt='配圖' style='max-width:100%'></p>";
}
echo "<pre>";
print_r($data); // 完整結構參考
echo "</pre>";
curl 替代 file_get_contents,支援超時控制、重試邏輯與 HTTPS(若 API 支援)。charset=utf-8,避免中文亂碼。// 封裝為可複用函式
function getIcibaDaily($date = null) {
$date = $date ?: date('Y-m-d');
$url = "https://open.iciba.com/dsapi/?date={$date}";
$json = @file_get_contents($url);
return $json ? json_decode($json, true) : false;
}
// 整合至 Laravel/ThinkPHP 控制器
public function dailyQuote() {
$data = getIcibaDaily();
return response()->json([
'success' => !!$data,
'data' => $data ?: ['msg' => '獲取失敗']
]);
}
透過簡單幾行代碼即可接入優質雙語內容,為您的應用增添每日驚喜元素。