- 将需要翻译的语言文件统一放在一个文件夹下面 命名为 language
- 遍历文件 获取文件中的所有中文词组 $this->get_all_language();
- 翻译中文词组 , 多次循环执行,一次执行50个的目的是因为会超时 $this->translate();
- 将中文词组按照从大到小排列 目的是为了防止词组遍历翻译错误 且遍历文件将翻译后的文字写入文件原位置 $this->sort_language();
## 遍历文件 获取文件中的所有中文词组
public function get_all_language()
{
# CMF_ROOT 项目根目录路径 返回文件夹绝对路径
$path = realpath(CMF_ROOT . '/language/');
# 获取文件夹中的所有文件
$patg_arr = $this->getDir($path);
$new_array = [];
## 遍历文件
foreach ($patg_arr as $file) {
## 获取单个文件内容
$content1 = file_get_contents($file);
## 通过正则表达式获取文件中的中文
preg_match_all('/[\x{4e00}-\x{9fff}]+/u', $content1, $content);
## 去除重复中文
foreach ($content[0] as $value2) {
$new_array[$value2] = '';
}
}
## 获取所有的中文词组
cache('language', $new_array);
}
## 翻译中文词组 , 多次循环执行,一次执行50个的目的是因为会超时
public function translate()
{
$content = cache('language');
$number = 0;
foreach ($content as $key=>$value) {
if(!$value&&$number<50){
$number++;
## 通过百度翻译API翻译
$BaiduController = new Baidu();
$result = $BaiduController->do_request($key,'zh','lao');
$en = $result['trans_result'][0]['dst'];
$content[$key] = $en;
cache('language',$content);
}
}
}
## 将中文词组按照从大到小排列 目的是为了防止词组遍历翻译错误 且遍历文件将翻译后的文字写入文件原位置
public function sort_language()
{
$content = cache('language');
$new_array = [];
foreach ($content as $key => $value) {
$new_array[] = $key;
}
usort($new_array, function ($a, $b) {
return (strLen($a) < strLen($b));
});
$new = [];
foreach ($new_array as $key => $value) {
$new[$value] = $content[$value];
}
cache('language',$new);
## 遍历文件将翻译后的文字写入文件原位置
$this->last_language();
}
## 遍历文件将翻译后的文字写入文件原位置
private function last_language()
{
$language = cache('language');
$path = realpath(CMF_ROOT . '/language/');
$patg_arr = $this->getDir($path);
foreach ($patg_arr as $file) {
$content1 = file_get_contents($file);
foreach ($language as $key => $value) {
$content1 = str_replace($key, $value, $content1);
}
file_put_contents($file, $content1);
}
}
##遍历方法
private function getDir($path)
{
//判断目录是否为空
if (!file_exists($path)) {
return [];
}
$files = scandir($path);
$fileItem = [];
foreach ($files as $v) {
$newPath = $path . DIRECTORY_SEPARATOR . $v;
if (is_dir($newPath) && $v != '.' && $v != '..') {
$fileItem = array_merge($fileItem, $this->getDir($newPath));
} else if (is_file($newPath)) {
$fileItem[] = $newPath;
}
}
return $fileItem;
}
源代码下载地址
https://gitee.com/xiakai123/yuyanbaozhizuo