PHP 利用 Excel 生成本地化语言文件

开始之前我们要先准备一个好了的文件给到翻译那边,那边按照要求进行翻译即可,然后我们对翻译后的内容转换为 JSON 文件,laravel thinkphp vue 现在都是直接可以使用了的。

按照需要的依赖。

1
$ composer require phpoffice/phpspreadsheet -vvv

index.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<?php

require_once __DIR__ . '/vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\IOFactory;

// 加载我们的数据文件
$spreadsheet = IOFactory::load(__DIR__ . '/data.xlsx');

$sheet = $spreadsheet->getActiveSheet();

// 获取表格数据
$sheet_data = $sheet->toArray(null, true, true, true);

// 默认KEY所在列
$key_index = 'C';

// 获取第3行的语言key
foreach ($sheet_data[3] as $key => $lang) {
if (!$lang) continue;

$data = [];

// 循环表格所有数据
foreach ($sheet_data as $index => $item) {
if ($index <= 3) continue;

// 如果有固定 KEY 就使用或者采用默认 KEY
if (!is_null($item['A'])) {
$data[$item['A']] = $item[$key];
} else if (!is_null($item[$key_index])) {
$data[$item[$key_index]] = $item[$key];
}
}

// 文件生成
file_put_contents($lang . '.json', json_encode($data, JSON_UNESCAPED_UNICODE));
}

执行。

1
$ php index.php

zh-hans.json

1
2
3
4
5
{
"Home": "首页",
"Personal": "个人中心",
"Tips": "提示:\n看完文章你不留个言吗?"
}

en.json

1
2
3
4
5
{
"Home": "Home",
"Personal": "Personal",
"Tips": "Tip:\nDon't you leave a comment after reading the article?"
}

data.xlsx

往上