首页
归档
笔记
树洞
搜索
友言

文章详情

Interesting People Record Interesting.

/ PHP / 文章详情

PHP 获取每日BING图 并且缓存URL链接到本地JSON

Sonder
2020-10-27
1341字
3分钟
浏览 (3.5k)

复制代码
<?php
/*
    * @author www.liumingye.cn
*/
$filename = "./cache.json";
if (file_exists($filename) === false) {
    file_put_contents($filename, "");
}
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
$contents = json_decode($contents, true);

if (filesize($filename) === 0) {
    // echo "获取\r\n";
    getBingImg();
} else {
    if ($contents['time'] === date("Ymd")) {
        // echo "缓存\r\n";
        Header("Location: ".$contents['url']);
    } else {
        // echo "过期\r\n";
        getBingImg();
    }
}
function getBingImg() {
    $str = file_get_contents('http://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) {
        global $contents;
        if($contents['url'] !== $imgurl){
            global $filename;
            $data = array(
                "time" => date("Ymd") ,
                "url" => $imgurl
            );
            $data = json_encode($data);
            file_put_contents($filename, $data);
        }
        Header("Location: ".$imgurl);
        exit();
    } else {
        exit('error');
    }
}

转载于:https://www.liumingye.cn/archives/266.html

下一篇 / vue源码中值得学习的方法

🎯 相关文章

💡 推荐文章

🕵️‍♂️ 评论 (0)