用PHP抓取Bing(必应)背景当做网页背景

本篇将介绍如何使用PHP和Jquery来抓取Bing(必应)背景当做网页背景

首先需要编写一个类,然后需要利用XML来抓取其中的图片属性。

最后将图片的链接赋值给body的url。

首先写一个action类,然后定义一个initial的方法:

<?php
class action{

function _initial() {
$context = stream_context_create ( array (
'http' => array (
'header' => 'Accept: application/xml'
)
) );
$url = 'http://cn.bing.com/HPImageArchive.aspx?format=xml&idx=0&n=1';
$xml = file_get_contents ( $url, false, $context );
$xml = simplexml_load_string ( $xml );
$url = $xml->image->url;
$scripts = <<<Scripts
<script type="text/javascript">
$(document).ready(function(){
$('body').css("background-image","url(http://cn.bing.com/$url)");
});
</script>
Scripts;
echo $scripts;
}
}
?>

然后在使用的时候只需要将方法调用出来即可:

<html>
<head>
<style>
body{
background-repeat:no-repeat;
}
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<?php $new = new action();
$new->_initial(); ?>
</head>
</html>