必应每日一图(cn.bing.com),指的是 cn.bing.com 网站的背景图片每天00:00就会更新一张。
很多人都喜欢把这些图片当作壁纸(包括我,当然,我并不是手动更换的,而是通过一款软件《必应自动桌面》来实现每天自动更换壁纸,当然,我们的主题是 如何用PHP抓取必应的每日背景图 )。
Bing的每日背景图片官方都有一个接口,一个是 json 方式,一个是 XML 的方式,所以就有了下面的这两个地址。
1. http:
2. http:
根据上面接口的参数,我大致得出了以下3个参数的解析:
1. format,非必要。我理解为输出格式,不存在或者不等于js,即为xml格式,等于js时,输出json格式;
2. idx,非必要。不存在或者等于0时,输出当天的图片,-1为已经预备用于明天显示的信息,1则为昨天的图片,idx最多获取到前16天的图片信息;*
3. n,必要。这是输出信息的数量,比如n=1,即为1条,以此类推,至多输出8条。
有兴趣的同学可以去研究上面的接口吧,接下来我来贴代码了,我是调用的第二个接口(返回格式是 XML
):
<?php
ini_set('date.timezone','Asia/Shanghai');
$tomorrow=strtotime(date('Y-m-d 00:00:00',strtotime('+1 day')));
$cache_time=$tomorrow-time();
$modified_time=@$_SERVER['HTTP_IF_MODIFIED_SINCE'];
if(strtotime($modified_time)+$cache_time>time()){
header("HTTP/1.1 304");
}else{
$str=curl_get('http://cn.bing.com/HPImageArchive.aspx?idx=0&n=1');
if(preg_match("/<url>(.+?)<\/url>/ies",$str,$matches)){
$imgurl='http://cn.bing.com'.$matches[1];
}
if($imgurl){
header('Content-Type: image/JPEG');
header ("Last-Modified: ".gmdate("D, d M Y H:i:s", time() )." GMT");
header ("Expires: ".gmdate("D, d M Y H:i:s", time()+$cache_time )." GMT");
header ("Cache-Control: max-age=$cache_time");
@ob_end_clean();
@readfile($imgurl);
@flush();
@ob_flush();
die;
}else{
die('error, please try again !');
}
}
function curl_get($url,$time_out=10){
$ch=curl_init($url);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch,CURLOPT_USERAGENT, 'Mozilla/5.0 (Linux; U; Android 4.4.1; zh-cn; R815T Build/JOP40D) AppleWebKit/533.1 (KHTML, like Gecko)Version/4.0 Chrome/4.5 Mobile Safari/533.1');
curl_setopt($ch,CURLOPT_TIMEOUT, $time_out);
$content=curl_exec($ch);
curl_close($ch);
return($content);
}
?>
Demo: https://www.ogdn.net/assets/img/bingimg.php //仅供演示用,不能用此链接作网站背景链接,因为有防盗链,你弄到网站当背景图也不会显示,要是真有需要,请在下方留言,我抽空做一个外链