mvc控制器类的访问-参数解析-谷歌翻译接口数据渲染到页面
- 编写一个类来处理mvc的控制器访问与参数解析;
- 选择一个接口数据来获取,并渲染到页面
1. 编写一个类来处理mvc的控制器访问与参数解析
namespace Mvc;
// 参数控制器
class ArgsController
{
public function show(...$args)
{
$res = sprintf('控制器: %s<br>', __CLASS__);
$res .= sprintf('方法: %s<br>', __FUNCTION__);
for ($i = 0; $i < count($args); $i++) {
$res .= sprintf('第 %d 个参数: %s<br>', $i + 1, $args[$i]);
}
return $res;
}
}
// 分割 path info 并过滤空值数组
$arrs = array_filter(explode('/', $_SERVER['PATH_INFO']));
// 解析出控制器
$controller = __NAMESPACE__ . '\\' . ucfirst(array_shift($arrs)) . 'Controller';
// 解析出方法
$method = array_shift($arrs);
// 解析出参数数组
$params = [];
for ($i = 0; $i < count($arrs); $i += 2) {
if (isset($arrs[$i + 1])) $params[$arrs[$i]] = $arrs[$i + 1];
}
// 传参调用控制器中的方法
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 改写函数,进行谷歌翻译
<?php
/**
* 发起网络请求函数二改版
* @param $url 请求的URL
* @param bool $params 请求的参数内容
* @param int $ispost 是否POST请求
* @return bool|string 返回内容
*/
function juheHttpRequest($url, $params = false, $ispost = 0)
{
$httpInfo = array();
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
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');
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
curl_setopt($ch, CURLOPT_TIMEOUT, 12);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// 添加 ssl 支持
if (preg_match('/^https:\/\//i', $url)) {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
}
if ($ispost) {
curl_setopt($ch, CURLOPT_POST, true);
// 注释并改为添加 http_build_query 不然请求不成功?
// curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
curl_setopt($ch, CURLOPT_URL, $url);
} else {
if ($params) {
// 注释并改为添加 http_build_query 不然请求不成功?
curl_setopt($ch, CURLOPT_URL, $url . '?' . http_build_query($params));
// curl_setopt($ch, CURLOPT_URL, $url . '?' . $params);
} else {
curl_setopt($ch, CURLOPT_URL, $url);
}
}
$response = curl_exec($ch);
if ($response === false) {
// echo "cURL Error: ".curl_error($ch);
return false;
}
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$httpInfo = array_merge($httpInfo, curl_getinfo($ch));
curl_close($ch);
return $response;
}
$url = 'https://translate.google.cn/translate_a/single';
$params = [
'client' => 'gtx',
'dt' => 't',
'dj' => 1,
'ie' => 'UTF-8',
'sl' => 'auto',
'tl' => 'zh', // 目标语言 zh 中文 | en 英语 | ru 俄语 等
'q' => 'hello world!', // 翻译字符串
];
// print_r(juheHttpRequest($url, array_merge($params, ['tl' => 'zh', 'q' => 'hello world!'])));
// 正确返回
// {"sentences":[{"trans":"你好,世界!","orig":"hello world!","backend":1}],"src":"en","confidence":0.8180167,"spell":{},"ld_result":{"srclangs":["en"],"srclangs_confidences":[0.8180167],"extended_srclangs":["en"]}}
// POST action = translate 供 ajax 请求翻译
if (isset($_POST['action']) && $_POST['action'] === 'translate') {
$q = $_POST['q'] ?? '';
$to = $_POST['to'];
$params = array_merge($params, ['q' => $q, 'tl' => $to]);
$res = juheHttpRequest($url, $params);
die($res);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.translate {
display: flex;
justify-content: center;
}
.translate>* {
margin: .2em;
}
.translate>select,
.translate>button {
height: 2em;
align-self: center;
}
</style>
</head>
<body>
<form class="translate" name="translate">
<textarea name="q" cols="30" rows="10"></textarea>
<select name="to">
<option value="zh">zh - 中文</option>
<option value="en">en - 英语</option>
<option value="ru">ru - 俄语</option>
</select>
<button type="button" name="btn">翻译</button>
<textarea name="res" cols="30" rows="10"></textarea>
</form>
<script>
// 翻译请求
const form = document.forms.translate;
form.btn.addEventListener('click', () => {
// 创建对象
const xhr = new XMLHttpRequest;
// 配置参数
xhr.open('post', '<?= $_SERVER['PHP_SELF'] ?>');
// 响应类型
xhr.responseType = 'json';
// 处理请求
xhr.onload = () => {
let trans = ''
if (typeof xhr.response.sentences !== 'undefined') {
let sentences = xhr.response.sentences;
for (let sentence of sentences) {
trans += sentence.trans;
}
}
// 显示翻译内容
form.res.value = trans;
};
// 发送数据
data = new FormData();
data.append('q', form.q.value);
data.append('to', form.to.value);
data.append('action', 'translate');
xhr.send(data);
});
</script>
</body>
</html>
- 运行 0305-2.php 输入
hello world!
点击翻译,翻译效果图