代码解析:随机展示 bing 每日一图

很久前码的一小段代码,偶然翻出来了。带注释分享一下,仅供大家研究学习,切勿用于其他用途。

方法一、用JSON取出

$bing = 'https://www.bing.com/';
// 请求接口
$data = file_get_contents($bing . 'HPImageArchive.aspx?format=js&idx=' .  mt_rand(0, 7) . '&n=1');
// 解析JSON数据
$data = json_decode($data, true);
// 转向图片
header('Location: ' . $bing . $data['images'][0]['url']);

方法二、用正则取出

<?php
$bing = 'https://www.bing.com';
// 请求接口
$body = file_get_contents($bing . '/HPImageArchive.aspx?idx=' .  mt_rand(0, 7) . '&n=1');
// 正则解析XML
if (preg_match('/<url>(.+)<\/url>/', $body, $matches)) {
    header('Location: ' . $bing . $matches[1]);
}
文章作者: 若海; 原文链接: https://www.rehiy.com/post/496/; 转载需声明来自技术写真 - 若海

添加新评论