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格式写入文件?
基础教程推荐
- 如何替换eregi() 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
