首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 獲取 Bing 每日壁紙並直接輸出圖片流

     編輯:PHP 相關知識

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;
?>

進階優化建議

  1. 本地緩存:避免每次請求都回源 Bing,建議將圖片保存到本地(文件/Redis/對象存儲),每天定時任務更新一次。
    $cacheFile = __DIR__ . '/cache/bing_' . date('Ymd') . '.jpg';
    if (!file_exists($cacheFile)) {
        $imageData = file_get_contents($imageUrl);
        file_put_contents($cacheFile, $imageData);
    }
    readfile($cacheFile);
  2. 支持多種分辨率:Bing URL 中包含分辨率標識(如 _1920x1080.jpg),可根據 User-Agent 或參數動態替換為 _UHD.jpg(4K)、_1366x768.jpg 等。
  3. 錯誤降級:失敗時返回預設佔位圖或 302 跳轉至靜態默認壁紙,避免前端顯示破碎圖標。
  4. HTTPS 強制:確保所有請求使用 HTTPS,防止混合內容警告。

前端調用示例

<!-- 直接作為圖片源 -->
<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 等)作為替代。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved