微軟必應(Bing)有個很不錯的設計:每天都換一張背景圖,而且品質普遍很高,值得收藏。其實我們可以用 PHP 把必應的背景圖以及當日的圖片介紹抓下來。
抓取背景圖的程式碼如下:
<?php
//獲取圖片XML信息
$url=file_get_contents('https://cn.bing.com/HPImageArchive.aspx?idx=0&n=1');
//從XML文件中找到圖片的URL
if(preg_match("/<url>(.+?)<\/url>/ies",$url,$matches)){
//生成圖片的URL
$imgurl='https://cn.bing.com'.$matches[1];
}
if($imgurl){
//輸出圖片
header('Content-Type: image/JPEG');
@ob_end_clean();
@readfile($imgurl);
@flush();
@ob_flush();
exit();
}else{
exit('error');
}
?>
效果示意:
第五行 preg_match 函數的第一個參數「/<url>(.+?)<\/url>/ies」是一條正則規則,只要把標籤換掉就能取到 XML 裡的其他欄位。例如改成「<copyright>」就能拿到當日的版權說明文字:
<?php
//獲取圖片XML信息
$url=file_get_contents('https://cn.bing.com/HPImageArchive.aspx?idx=0&n=1');
//從XML文件中找到圖片的版權介紹
if(preg_match("/<copyright>(.+?)<\/copyright>/ies",$url,$matches)){
//生成圖片的版權介紹
$imgcopyright=$matches[1];
}
if($imgcopyright){
//輸出圖片版權介紹
header("Content-type: text/html; charset=utf-8");
echo $imgcopyright;
}else{
exit('error');
}
?>
把兩段邏輯合起來,就能做成一個每天自動更新的必應桌布與圖說頁面。