我有一堆不是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); } }如何以utf-8编码保存文件?
3 回答
![?](http://img1.sycdn.imooc.com/545862e700016daa02200220-100-100.jpg)
至尊宝的传说
TA贡献1789条经验 获得超10个赞
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);
或者,使用PHP的流过滤器:
$fd = fopen($file, 'r');
stream_filter_append($fd, 'convert.iconv.UTF-8/OLD-ENCODING');
stream_copy_to_stream($fd, fopen($output, 'w'));
![?](http://img1.sycdn.imooc.com/54584cde0001d19202200220-100-100.jpg)
万千封印
TA贡献1891条经验 获得超3个赞
<?php
函数writeUTF8File($ filename,$ content){
$ f = fopen($ filename,“ w”);
#现在UTF-8-添加字节顺序标记
fwrite($ f,pack(“ CCC”,0xef,0xbb,0xbf));
fwrite($ f,$ content);
fclose($ f);
}
?>
- 3 回答
- 0 关注
- 1108 浏览
添加回答
举报
0/150
提交
取消