本文介紹了如何以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格式寫入文件?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!