Correcting teacher:灭绝师太
Correction status:qualified
Teacher's comments:博客内容不错, 是我们还没讲到的内容~
url: http://php.io/PHP/0305/0305test/index.php/weather/get/city/%E5%8D%97%E9%98%B3
<?php
namespace test0305\controllers;
class InitializeControllers
{
public function initialize()
{
$pathinfoArr = array_filter(explode('/', $_SERVER['PATH_INFO']));
$controller = __NAMESPACE__ . '\\' . ucfirst(array_shift($pathinfoArr)) . 'Controllers';
$action = array_shift($pathinfoArr);
$params = ['key' => '你自己的聚合接口的key'];
for ($i = 0; $i < count($pathinfoArr); $i += 2) {
if (isset($pathinfoArr[$i + 1])) {
$params[$pathinfoArr[$i]] = $pathinfoArr[$i + 1];
}
}
echo '<pre>' . print_r($params, true) . '</pre>';
echo $controller . ':' . $action . '<hr>';
// $data = call_user_func_array([new $controller, $action], $params);
// echo $data;
}
}
<?php
namespace test0305\controllers;
class WeatherControllers
{
/**
* 接口请求: 获取天气信息
*
* @params $params: 数组参数['city(城市)','key(聚合接口的key)']
*/
public function getWeather(array $params)
{
$query = http_build_query($params);
// 接口请求初始化
$ch = curl_init();
// 设置请求选项
curl_setopt_array($ch, [
// url
CURLOPT_URL => 'http://apis.juhe.cn/simpleWeather/query?' . $query,
// 请求方式为get
CURLOPT_HTTPGET => true,
// 是否设置请求头
CURLOPT_HEADER => false,
// 设置是否返回并输出
CURLOPT_RETURNTRANSFER => true
]);
// 结束请求
$api = curl_exec($ch);
if (json_decode($api, true)['error_code'] !== 0) {
echo json_decode($api, true)['reason'];
} else {
if (file_exists(dirname(__DIR__) . '../../html/' . lcfirst(ltrim(__FUNCTION__, 'get')) . '.php')) {
include dirname(__DIR__) . '../../html/' . lcfirst(ltrim(__FUNCTION__, 'get')) . '.php';
} else {
exit('文件写入失败');
}
}
}
}