微軟的必應搜索的每日圖片不得不說,都是經典,美得一塌糊涂。
看到很多把必應壁紙做電腦壁紙的軟件,今天閑的蛋疼,就折騰了一下。
接口
我們用到的接口是https://cn.bing.com/HPImageArchive.aspx?idx=0&n=1
這里的idx=0
表示是顯示當天的時間,如果要顯示昨天的就將idx=0
改為idx=1
,以此類推。
注意:bing支持查看歷史圖片15天以內的,數字就有范圍限制了(0-15)。
獲取當日圖片
我們有了接口就可以直接利用正則表達式去匹配相關字符串了。
下面給出一個獲取并輸出當日美圖的php代碼
<?php $str=file_get_contents('https://cn.bing.com/HPImageArchive.aspx?idx=0&n=1'); if (preg_match("/<url>(.+?)<\/url>/ies", $str, $matches)) { $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'); } ?>
保存為bingpic.php,上傳到服務器直接訪問即可。
獲取圖片版權介紹
有了圖片,沒有文字怎么能滿足饑渴的我,還是利用正則提取出圖片版權信息
<?php $url=file_get_contents('https://cn.bing.com/HPImageArchive.aspx?idx=0&n=1'); 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'); } ?>
tip:修改相關參數即可實現對應的文字說明
自動保存bing圖片
自動在php文件同級目錄下創建一個當前年月的文件夾,保存每天的bing美圖并輸出
<?php error_reporting(0); $path=date('Ym'); if (!file_exists($path)) { mkdir($path, 0777); } $pathurl = $path.'/'.date('d').'.jpg'; if (!is_file($pathurl)) { $str=file_get_contents('https://cn.bing.com/HPImageArchive.aspx?idx=0&n=1'); if (preg_match("/<urlBase>(.+?)<\/urlBase>/ies", $str, $matches)) { $imgurl='https://s.cn.bing.com'.$matches[1].'_1920x1080.jpg'; copy($imgurl, $pathurl); } } header('Content-Type: image/JPEG'); @ob_end_clean(); @readfile($pathurl); @flush(); @ob_flush(); exit(); ?>
轉載請注明出處 AE博客|墨淵 ? 使用PHP獲取必應Bing每日圖片
發表評論