建立于: 2年前 ( 更新: 2年前 )
您是否有大量的big5编码的php、js或html页面需要转码?
这里提供一个我原创的php转码方式,用PHP的进程进行文件的转码。
数据库big5 via latin1的转码更为复杂,本文就不做讨论啦。
转码前最重要的一件事是对您的目标数据夹进行版控,这样转码后,您可以比较是否有正常转码成功。
或是有问题时还可以施展还原大法。
以下的这只进程的动作非常简单,应该看code都猜的出来他在做什么,就是循环参数下的目录内所有副档是php、js或html的文件,
换掉里面的charset并且把编码换成UTF8。
要运行这支进程,请确认您的电脑中有安装php,例如我的php运行进程是在/usr/bin/php中,如果不是可以自己调整#!/usr/bin/php正确的位置。
您能透过which php的命令,检测您的电脑中php的位置,例如MacOS可能的结果会像下方这样
which php
/opt/homebrew/bin/php
当然,您的结果也很可能是
which php
php not found
在没有安装php电脑,也可用Docker挂载目录的方式进行,这是就题外话了,本文不多做介绍。
进入正题,让我们开始吧!
一、首先,创建一个文件叫 iconv.php
#!/usr/bin/php
<?php
if(count($argv)>1){
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($argv[1]));
array_filter(iterator_to_array($iterator), function($item) {
if($item->isFile()){
$file = sprintf("%s/%s",$item->getPath(),$item->getFilename());
if(preg_match('/(\.(php|js|html)$)/', $file, $matches, PREG_OFFSET_CAPTURE)) {
$output = file_get_contents($file);
if(!mb_check_encoding($output, 'UTF-8'))
{
echo sprintf("转换big5文件为utf8: %s\n", $item->getFilename());
$output_utf8 = mb_convert_encoding($output, "UTF-8", "BIG5");
$output_utf8 = preg_replace("/charset=big5/", "charset=utf-8", $output_utf8);
file_put_contents($file, $output_utf8);
}
}
}
});
} else {
echo sprintf("%s [转档的目录]", $argv[0]);
}
二、再来,将这支php变更为可以运行的文件,+x让文件有可运行的权限。
chmod +x iconv.php
三、最后,有了这支转码进程后,我们就可以在终端机运行罗。
以下为示意图,例如我要转码的进程是在/var/www/html目录下。
./iconv.php /var/www/html
转换big5文件为utf8: abc.php
转换big5文件为utf8: test.php
四、转码完成,可以到目标目录,例如我是/var/www/html,用git diff查看是否有什么异常
可以看到,这支转码进程,除了帮我们转换编码,也协助我们把code改掉罗
diff --git a/abc.php b/abc.php
index 3bee6ed..5797c23 100644
--- a/abc.php
+++ b/abc.php
@@ -2,13 +2,13 @@
<html>
<head>
<title>Page Title</title>
-<meta http-equiv="content-type" content="text/html; charset=big5">
+<meta http-equiv="content-type" content="text/html; charset=utf-8">
</head>
<body>
<h1>This is a Heading</h1>
<p>This is a paragraph.</p>
-<A4><A4><A4><E5>
+中文
</body>
</html>
diff --git a/test.php b/test.php
index 3bee6ed..5797c23 100644
--- a/test.php
+++ b/test.php
No Comment
Post your comment