Blogger Information
Blog 70
fans 1
comment 0
visits 53102
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
mvc控制器类的访问-参数解析-谷歌翻译接口数据渲染到页面
葡萄枝子
Original
731 people have browsed it

mvc控制器类的访问-参数解析-谷歌翻译接口数据渲染到页面

  1. 编写一个类来处理mvc的控制器访问与参数解析;
  2. 选择一个接口数据来获取,并渲染到页面

1. 编写一个类来处理mvc的控制器访问与参数解析

  • 新建 0305.php
  1. namespace Mvc;
  2. // 参数控制器
  3. class ArgsController
  4. {
  5. public function show(...$args)
  6. {
  7. $res = sprintf('控制器: %s<br>', __CLASS__);
  8. $res .= sprintf('方法: %s<br>', __FUNCTION__);
  9. for ($i = 0; $i < count($args); $i++) {
  10. $res .= sprintf('第 %d 个参数: %s<br>', $i + 1, $args[$i]);
  11. }
  12. return $res;
  13. }
  14. }
  15. // 分割 path info 并过滤空值数组
  16. $arrs = array_filter(explode('/', $_SERVER['PATH_INFO']));
  17. // 解析出控制器
  18. $controller = __NAMESPACE__ . '\\' . ucfirst(array_shift($arrs)) . 'Controller';
  19. // 解析出方法
  20. $method = array_shift($arrs);
  21. // 解析出参数数组
  22. $params = [];
  23. for ($i = 0; $i < count($arrs); $i += 2) {
  24. if (isset($arrs[$i + 1])) $params[$arrs[$i]] = $arrs[$i + 1];
  25. }
  26. // 传参调用控制器中的方法
  27. echo call_user_func_array([(new $controller), $method], $params);
  • 运行 http://php/0305.php/args/show/id/1/admin/msg/hello+world!?x=a&y=b

参数控制器

2. 选择一个接口数据来获取,并渲染到页面

  • 新建 0305-2.php 改写函数,进行谷歌翻译
  1. <?php
  2. /**
  3. * 发起网络请求函数二改版
  4. * @param $url 请求的URL
  5. * @param bool $params 请求的参数内容
  6. * @param int $ispost 是否POST请求
  7. * @return bool|string 返回内容
  8. */
  9. function juheHttpRequest($url, $params = false, $ispost = 0)
  10. {
  11. $httpInfo = array();
  12. $ch = curl_init();
  13. curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
  14. curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36');
  15. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
  16. curl_setopt($ch, CURLOPT_TIMEOUT, 12);
  17. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  18. // 添加 ssl 支持
  19. if (preg_match('/^https:\/\//i', $url)) {
  20. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  21. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  22. }
  23. if ($ispost) {
  24. curl_setopt($ch, CURLOPT_POST, true);
  25. // 注释并改为添加 http_build_query 不然请求不成功?
  26. // curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
  27. curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
  28. curl_setopt($ch, CURLOPT_URL, $url);
  29. } else {
  30. if ($params) {
  31. // 注释并改为添加 http_build_query 不然请求不成功?
  32. curl_setopt($ch, CURLOPT_URL, $url . '?' . http_build_query($params));
  33. // curl_setopt($ch, CURLOPT_URL, $url . '?' . $params);
  34. } else {
  35. curl_setopt($ch, CURLOPT_URL, $url);
  36. }
  37. }
  38. $response = curl_exec($ch);
  39. if ($response === false) {
  40. // echo "cURL Error: ".curl_error($ch);
  41. return false;
  42. }
  43. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  44. $httpInfo = array_merge($httpInfo, curl_getinfo($ch));
  45. curl_close($ch);
  46. return $response;
  47. }
  48. $url = 'https://translate.google.cn/translate_a/single';
  49. $params = [
  50. 'client' => 'gtx',
  51. 'dt' => 't',
  52. 'dj' => 1,
  53. 'ie' => 'UTF-8',
  54. 'sl' => 'auto',
  55. 'tl' => 'zh', // 目标语言 zh 中文 | en 英语 | ru 俄语 等
  56. 'q' => 'hello world!', // 翻译字符串
  57. ];
  58. // print_r(juheHttpRequest($url, array_merge($params, ['tl' => 'zh', 'q' => 'hello world!'])));
  59. // 正确返回
  60. // {"sentences":[{"trans":"你好,世界!","orig":"hello world!","backend":1}],"src":"en","confidence":0.8180167,"spell":{},"ld_result":{"srclangs":["en"],"srclangs_confidences":[0.8180167],"extended_srclangs":["en"]}}
  61. // POST action = translate 供 ajax 请求翻译
  62. if (isset($_POST['action']) && $_POST['action'] === 'translate') {
  63. $q = $_POST['q'] ?? '';
  64. $to = $_POST['to'];
  65. $params = array_merge($params, ['q' => $q, 'tl' => $to]);
  66. $res = juheHttpRequest($url, $params);
  67. die($res);
  68. }
  69. ?>
  70. <!DOCTYPE html>
  71. <html lang="en">
  72. <head>
  73. <meta charset="UTF-8">
  74. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  75. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  76. <title>Document</title>
  77. <style>
  78. .translate {
  79. display: flex;
  80. justify-content: center;
  81. }
  82. .translate>* {
  83. margin: .2em;
  84. }
  85. .translate>select,
  86. .translate>button {
  87. height: 2em;
  88. align-self: center;
  89. }
  90. </style>
  91. </head>
  92. <body>
  93. <form class="translate" name="translate">
  94. <textarea name="q" cols="30" rows="10"></textarea>
  95. <select name="to">
  96. <option value="zh">zh - 中文</option>
  97. <option value="en">en - 英语</option>
  98. <option value="ru">ru - 俄语</option>
  99. </select>
  100. <button type="button" name="btn">翻译</button>
  101. <textarea name="res" cols="30" rows="10"></textarea>
  102. </form>
  103. <script>
  104. // 翻译请求
  105. const form = document.forms.translate;
  106. form.btn.addEventListener('click', () => {
  107. // 创建对象
  108. const xhr = new XMLHttpRequest;
  109. // 配置参数
  110. xhr.open('post', '<?= $_SERVER['PHP_SELF'] ?>');
  111. // 响应类型
  112. xhr.responseType = 'json';
  113. // 处理请求
  114. xhr.onload = () => {
  115. let trans = ''
  116. if (typeof xhr.response.sentences !== 'undefined') {
  117. let sentences = xhr.response.sentences;
  118. for (let sentence of sentences) {
  119. trans += sentence.trans;
  120. }
  121. }
  122. // 显示翻译内容
  123. form.res.value = trans;
  124. };
  125. // 发送数据
  126. data = new FormData();
  127. data.append('q', form.q.value);
  128. data.append('to', form.to.value);
  129. data.append('action', 'translate');
  130. xhr.send(data);
  131. });
  132. </script>
  133. </body>
  134. </html>
  • 运行 0305-2.php 输入 hello world! 点击翻译,翻译效果图

谷歌翻译

  • 左边输入你好,世界! 选择英文,点击翻译

中文翻英文

  • 点击下拉菜单,将中文翻译成俄文

中文翻俄文

Correcting teacher:天蓬老师天蓬老师

Correction status:qualified

Teacher's comments:非常OK
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