php 获取Bing首页壁纸并保存至本地

<?php

define(‘WALLPAPER_PATH‘,‘C:/xxx/xxx‘); //本地目录

class BingPicture{
    
    private $content = "";
    private $imgurl = "";
    
    public function __construct() {
        $this->_getWallpaperUrl();
    }
    
    //获取壁纸
    public function _getWallpaperUrl(){
        if (!function_exists(‘file_get_contents‘)) 
            return false;
        
        $this->content=file_get_contents(‘https://cn.bing.com/HPImageArchive.aspx?idx=0&n=1‘);
        
        if (preg_match("/<url>(.+?)<\/url>/ies", $this->content, $matches)) {
            $this->imgurl=‘https://cn.bing.com‘.$matches[1];
        }
    }
    
    //获取壁纸信息
    public function getWallpaperInfo(){
        if (preg_match("/<copyright>(.+?)<\/copyright>/ies", $this->content, $matches)) {
            $imgcopyright=$matches[1];
        }
        
        if($imgcopyright){
            return $imgcopyright;
        }
    }
    
    //保存壁纸    
    public function saveWallpaper() {
        
        if(!file_exists(WALLPAPER_PATH)){
            mkdir(WALLPAPER_PATH, 0777);
        }
        
        $url = $this->imgurl;
        $pic = ‘Bing‘.date("Ymd").‘.jpg‘;
        $file = WALLPAPER_PATH.‘/‘.$pic;
        
    if ($url == "")
        return false;
            
        if(file_exists($file))
                return true;

    ob_start ();
    readfile ( $url );
    $img = ob_get_contents ();
    ob_end_clean ();
    $size = strlen ( $img );
        
        $fp2 = @fopen ( WALLPAPER_PATH . DIRECTORY_SEPARATOR . $pic, "a" );
        fwrite ( $fp2, $img );
        fclose ( $fp2 );
    }
    
}

以及创建任务计划定时执行脚本

@echo off

rem 定时获取并保存Bing壁纸脚本

cd /d F:

rem php.exe所在目录
set PHP_PATH=F:\xxx

rem 脚本所在目录
start %PHP_PATH% -q F:\xxxx\xxx.php

exit

php

相关推荐