我有一堆不是 UTF-8 编码的文件,我正在将网站转换为 UTF-8 编码.
I have bunch of files that are not in UTF-8 encoding and I'm converting a site to UTF-8 encoding.
我对要保存为 utf-8 的文件使用了简单的脚本,但这些文件以旧编码保存:
I'm using simple script for files that I want to save in utf-8, but the files are saved in old encoding:
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);
}
}
如何以 utf-8 编码保存文件?
How can I save files in utf-8 encoding?
file_get_contents/file_put_contents 不会神奇地转换编码.
file_get_contents / file_put_contents will not magically convert encoding.
你必须显式地转换字符串;例如 iconv()
或 mb_convert_encoding()
.
You have to convert the string explicitly; for example with iconv()
or mb_convert_encoding()
.
试试这个:
$data = file_get_contents($npath);
$data = mb_convert_encoding($data, 'UTF-8', 'OLD-ENCODING');
file_put_contents('tempfolder/'.$a, $data);
或者,使用 PHP 的流过滤器:
Or alternatively, with PHP's stream filters:
$fd = fopen($file, 'r');
stream_filter_append($fd, 'convert.iconv.UTF-8/OLD-ENCODING');
stream_copy_to_stream($fd, fopen($output, 'w'));
这篇关于如何以UTF-8格式写入文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!