Sta*_*ter 45 php encoding utf-8 iconv mbstring
我有一堆不是UTF-8编码的文件,我正在将一个站点转换为UTF-8编码.
我正在使用简单的脚本来保存我想要保存在utf-8中的文件,但文件以旧编码保存:
header('Content-type: text/html; charset=utf-8');
mb_internal_encoding('UTF-8');
$fpath="folder";
$d=dir($fpath);
while (False !== ($a = $d->read()))
{
if ($a != '.' and $a != '..')
{
$npath=$fpath.'/'.$a;
$data=file_get_contents($npath);
file_put_contents('tempfolder/'.$a, $data);
}
}
Run Code Online (Sandbox Code Playgroud)
如何以utf-8编码保存文件?
use*_*584 70
添加物料清单:UTF-8
file_put_contents($myFile, "\xEF\xBB\xBF". $content);
Run Code Online (Sandbox Code Playgroud)
Arn*_*anc 47
file_get_contents/file_put_contents不会神奇地转换编码.
你必须明确地转换字符串; 例如用iconv()
或mb_convert_encoding()
.
试试这个:
$data = file_get_contents($npath);
$data = mb_convert_encoding($data, 'UTF-8', 'OLD-ENCODING');
file_put_contents('tempfolder/'.$a, $data);
Run Code Online (Sandbox Code Playgroud)
或者,使用PHP的流过滤器:
$fd = fopen($file, 'r');
stream_filter_append($fd, 'convert.iconv.UTF-8/OLD-ENCODING');
stream_copy_to_stream($fd, fopen($output, 'w'));
Run Code Online (Sandbox Code Playgroud)
Ala*_*laa 25
<?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); } ?>