Bing 首頁每日更新的高質量壁紙是許多開發者想要接入的素材源。本文提供一個極簡的 PHP 腳本,通過解析 Bing 官方 XML 接口獲取圖片 URL,並直接以圖片流形式輸出,可直接作為 <img src="bing.php"> 引用。
<?php
/**
* Bing 每日壁紙代理輸出
* 直接訪問此腳本即可獲取圖片二進制流
* 示例:<img src="bing_daily.php" alt="Bing 每日壁紙" />
*/
// 1. 獲取 Bing 官方 XML(idx=0 為今日,n=1 僅需一條)
$apiUrl = 'https://cn.bing.com/HPImageArchive.aspx?idx=0&n=1&format=xml';
$xmlContent = @file_get_contents($apiUrl);
if (!$xmlContent) {
// 靜默失敗或輸出佔位圖
header('HTTP/1.1 503 Service Unavailable');
exit('無法獲取 Bing 數據源');
}
// 2. 解析 XML 獲取圖片相對路徑
// 使用 SimpleXML 比正則更健壯
$xml = simplexml_load_string($xmlContent);
$relativeUrl = (string)($xml->images->image->url ?? '');
if (!$relativeUrl) {
header('HTTP/1.1 503 Service Unavailable');
exit('XML 解析失敗');
}
// 3. 拼接完整圖片 URL
$imageUrl = 'https://cn.bing.com' . $relativeUrl;
// 4. 獲取圖片二進制內容
$imageData = @file_get_contents($imageUrl);
if (!$imageData) {
header('HTTP/1.1 503 Service Unavailable');
exit('圖片下載失敗');
}
// 5. 輸出圖片流
header('Content-Type: image/jpeg');
header('Content-Length: ' . strlen($imageData));
header('Cache-Control: public, max-age=86400'); // 緩存 24 小時
header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 86400) . ' GMT');
echo $imageData;
exit;
?>
$cacheFile = __DIR__ . '/cache/bing_' . date('Ymd') . '.jpg';
if (!file_exists($cacheFile)) {
$imageData = file_get_contents($imageUrl);
file_put_contents($cacheFile, $imageData);
}
readfile($cacheFile);
_1920x1080.jpg),可根據 User-Agent 或參數動態替換為 _UHD.jpg(4K)、_1366x768.jpg 等。<!-- 直接作為圖片源 -->
<img src="bing_daily.php" alt="Bing 每日壁紙" style="width: 100%; max-width: 1920px;" />
<!-- 作為 CSS 背景 -->
<div style="background-image: url('bing_daily.php'); background-size: cover; height: 400px;"></div>
注意:Bing 官方未公開承諾此接口長期穩定可用,商業項目建議申請 Bing Image Search API 或使用無版權圖片庫(Unsplash、Pexels 等)作為替代。