自PbootCmsV2.0.6開始,PbootCMS支持自定義標簽,且升級不被覆蓋。媽媽再也不用擔心我的代碼升級被覆蓋啦。
於是就想到用這個功能定制一個每日一圖。
這個文件位置在 home下ExtLabelController控制器。
我們先找圖源。通過百度找到必應搜索的API。
地址是這個:
https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1
獲取到的是一串JSON,正是我們需要的。
用pbootcms自帶的get_url方法直接抓取一下就搞定。
上代碼:
//抓取必應每日一圖 public function getBingImage(){ $url = 'https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1'; $data = json_decode(get_url($url)); $result = $data->images[0]; $image = 'https://www.bing.com'.$result->url; return $image; }
然后再給自己定制一個標簽就好啦。
// 擴展單個標簽 private function diylabel() { $this->content = str_replace('{pboot:walle}', $this->getBingImage(), $this->content); }
最后只要在模板文件中寫上 {pboot:walle} 就調用出圖片地址。把這個放在 <img> 標簽中,或者放在 background 中,至此,搞定。
下面是整個ExtLabelController文件的代碼:
<?php /** * @copyright (C)2020-2099 AndyGuo . * @author AndyGuo * @email vip@d163.net * @date 2020年4月5日 * 個人擴展標簽可編寫到本類中,升級不會覆蓋 */ namespace app//home//controller; /* 此處雙斜杠需要換成單反斜杠*/ use core//basic//Controller; /* 此處雙斜杠需要換成單反斜杠*/ class ExtLabelController { protected $content; /* 必備啟動函數 */ public function run($content) { // 接收數據 $this->content = $content; // 執行個人自定義標簽函數 $this->diylabel(); // 返回數據 return $this->content; } // 擴展單個標簽 private function diylabel() { $this->content = str_replace('{pboot:walle}', $this->getBingImage(), $this->content); } //抓取必應每日一圖 public function getBingImage(){ $url = 'https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1'; $data = json_decode(get_url($url)); $result = $data->images[0]; $image = 'https://www.bing.com'.$result->url; return $image; } }
本文來源:http://www.d163.net/html/php/35.html -- 小郭博客(AndyGuo)