本文介绍了如何以UTF-8格式写文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用的是简单的脚本对于要保存在utf-8中的文件,但文件以旧的编码保存:
header('Content-键入:text / html; charset = utf-8');
mb_internal_encoding('UTF-8');
$ fpath =folder;
$ d = dir($ fpath);
while(False!==($ a = $ d-> read()))
{
if($ a!='。 ='..')
{
$ npath = $ fpath。'/'。$ a;
$ data = file_get_contents($ npath);
file_put_contents('tempfolder /'.$ a,$ data);
}
}
保存文件在utf-8编码?
解决方案
file_get_contents / file_put_contents不会神奇地转换编码。
你必须明确转换字符串;例如或。
尝试这样:
$ data = file_get_contents($ npath);
$ data = mb_convert_encoding($ data,'UTF-8','OLD-ENCODING');
file_put_contents('tempfolder /'.$ a,$ data);
或者,使用PHP的流过滤器:
$ fd = fopen($ file,'r');
stream_filter_append($ fd,'convert.iconv.UTF-8 / OLD-ENCODING');
stream_copy_to_stream($ fd,fopen($ output,'w'));
I have bunch of files that are not in UTF-8 encoding and I'm converting a site to UTF-8 encoding.
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);
}
}
How can I save files in utf-8 encoding?
解决方案
file_get_contents / file_put_contents will not magically convert encoding.
You have to convert the string explicitly; for example with iconv()
or mb_convert_encoding()
.
Try this:
$data = file_get_contents($npath);
$data = mb_convert_encoding($data, 'UTF-8', 'OLD-ENCODING');
file_put_contents('tempfolder/'.$a, $data);
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格式写文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!