2014-04-07 39 views
2

我有一个PHP应用程序的文件编码是希腊ISO(iso-8859-7)。我想将这些文件转换为utf-8,但仅仅使用utf-8保存这些文件是不够的,因为希腊文文本被乱码。有没有一个“自动”方法来做到这一点,以便我可以完全转换我的应用程序的编码,而不必通过每个文件并重写文本?转换文件编码

回答

4

在Linux系统上,如果你是确保所有文件都目前在ISO-8859-7编码,你可以这样做:

bash> find /your/path -name "*.php" -type f \ 
    -exec iconv "{}" -f ISO88597 -t UTF8 -o "{}.tmp" \; \ 
    -exec mv "{}.tmp" "{}" \; 

将其转换所有位于/your/path的PHP脚本文件以及所有的子目录。删除-name "*.php"以转换所有文件。


既然你是在Windows下,最简单的办法是一个PHP脚本是这样的:

<?php 
$path = realpath('C:\\your\\path'); 

$iterator = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($path), 
    RecursiveIteratorIterator::SELF_FIRST 
); 

foreach($iterator as $fileName => $file){ 
    if($file->isFile()) 
     file_put_contents(
      $fileName, 
      iconv('ISO-8859-7', 'UTF-8', file_get_contents($fileName)) 
     ); 
} 
+0

不幸的是我在一个Windows系统上。我可以使用Cygwin吗? – bikey77

+0

是的,你可以。但是上面的PHP代码片段应该可以完成这项工作吗? – RandomSeed

0

尝试iconv功能

$new_string = iconv("ISO-8859-7", "UTF-8", $old_string); 
+0

这只会转换内容,我想完全转换文件,包括内容。 – bikey77

+0

啊,我读了你的最后一句话,就是如何自动转换数据而不必手动重新输入。您将不得不编写自己的函数来横切您的应用程序并更新文件的编码。如果iconv不适合你,请尝试mb_convert_encoding(http://php.net/manual/en/function.mb-convert-encoding.php)。当你说文本变得乱码时,是在文本编辑器中查看文件时,还是在PHP中输出文件的内容? –

+0

不用担心。第二个。 – bikey77

1
<?php 
function writeUTF8File($filename,$content) { 
     $f=fopen($filename,"w"); 
     # Now UTF-8 - Add byte order mark 
     fwrite($f, pack("CCC",0xef,0xbb,0xbf)); 
     fwrite($f,$content); 
     fclose($f); 
} 

?> 
0

下面的代码应该为你工作,这是一个PowerShell脚本,你可以Start > Run > powershell并在修改所需的行后粘贴代码。

$sourcepath = "d:\temp\old\" 
$targetpath = "d:\temp\new\" 
foreach ($file in Get-ChildItem $sourcepath -Filter *.php -Recurse) { 
    $content = [System.IO.File]::ReadAllBytes($sourcepath + $file) 
    $str = [System.Text.Encoding]::GetEncoding("ISO-8859-7").GetString($content) 
    # $str = $str.Replace("ISO-8859-7", "UTF-8") 
    [System.IO.File]::WriteAllText($targetpath + $file, $str) 
} 

您可以删除# char 6行,在保存前进行一些替换。