How to write file in UTF-8 format?(如何以UTF-8格式写入文件?)
问题描述
我有一堆不是 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格式写入文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何以UTF-8格式写入文件?


- 如何在 Symfony2 中正确使用 webSockets 2021-01-01
- 使用 GD 和 libjpeg 支持编译 PHP 2022-01-01
- Laravel 5:Model.php 中的 MassAssignmentException 2021-01-01
- 如何使用 Google API 在团队云端硬盘中创建文件夹? 2022-01-01
- openssl_digest vs hash vs hash_hmac?盐与盐的区别HMAC? 2022-01-01
- PHP - if 语句中的倒序 2021-01-01
- PHP foreach() 与数组中的数组? 2022-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- 覆盖 Magento 社区模块控制器的问题 2022-01-01
- 如何从数据库中获取数据以在 laravel 中查看页面? 2022-01-01