Blogger Information
Blog 17
fans 1
comment 0
visits 14496
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
PHP: 解析pathinfo(从url解析控制器和方法) 和 cUrl的简单应用
zl的php学习博客
Original
844 people have browsed it

1. 解析pathinfo(从url解析控制器和方法)

  1. url: http://php.io/PHP/0305/0305test/index.php/weather/get/city/%E5%8D%97%E9%98%B3

效果图

效果图

代码

  1. <?php
  2. namespace test0305\controllers;
  3. class InitializeControllers
  4. {
  5. public function initialize()
  6. {
  7. $pathinfoArr = array_filter(explode('/', $_SERVER['PATH_INFO']));
  8. $controller = __NAMESPACE__ . '\\' . ucfirst(array_shift($pathinfoArr)) . 'Controllers';
  9. $action = array_shift($pathinfoArr);
  10. $params = ['key' => '你自己的聚合接口的key'];
  11. for ($i = 0; $i < count($pathinfoArr); $i += 2) {
  12. if (isset($pathinfoArr[$i + 1])) {
  13. $params[$pathinfoArr[$i]] = $pathinfoArr[$i + 1];
  14. }
  15. }
  16. echo '<pre>' . print_r($params, true) . '</pre>';
  17. echo $controller . ':' . $action . '<hr>';
  18. // $data = call_user_func_array([new $controller, $action], $params);
  19. // echo $data;
  20. }
  21. }

2. cUrl的简单应用

效果图

代码

  1. <?php
  2. namespace test0305\controllers;
  3. class WeatherControllers
  4. {
  5. /**
  6. * 接口请求: 获取天气信息
  7. *
  8. * @params $params: 数组参数['city(城市)','key(聚合接口的key)']
  9. */
  10. public function getWeather(array $params)
  11. {
  12. $query = http_build_query($params);
  13. // 接口请求初始化
  14. $ch = curl_init();
  15. // 设置请求选项
  16. curl_setopt_array($ch, [
  17. // url
  18. CURLOPT_URL => 'http://apis.juhe.cn/simpleWeather/query?' . $query,
  19. // 请求方式为get
  20. CURLOPT_HTTPGET => true,
  21. // 是否设置请求头
  22. CURLOPT_HEADER => false,
  23. // 设置是否返回并输出
  24. CURLOPT_RETURNTRANSFER => true
  25. ]);
  26. // 结束请求
  27. $api = curl_exec($ch);
  28. if (json_decode($api, true)['error_code'] !== 0) {
  29. echo json_decode($api, true)['reason'];
  30. } else {
  31. if (file_exists(dirname(__DIR__) . '../../html/' . lcfirst(ltrim(__FUNCTION__, 'get')) . '.php')) {
  32. include dirname(__DIR__) . '../../html/' . lcfirst(ltrim(__FUNCTION__, 'get')) . '.php';
  33. } else {
  34. exit('文件写入失败');
  35. }
  36. }
  37. }
  38. }
Correcting teacher:灭绝师太灭绝师太

Correction status:qualified

Teacher's comments:博客内容不错, 是我们还没讲到的内容~
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post