猿问

如何以UTF-8格式写入文件?

我有一堆不是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编码保存文件?


宝慕林4294392
浏览 1109回答 3
3回答

至尊宝的传说

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'));

慕标5832272

添加BOM:UTF-8file_put_contents($myFile, "\xEF\xBB\xBF".  $content); 

万千封印

<?php函数writeUTF8File($ filename,$ content){&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; $ f = fopen($ filename,“ w”);&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; #现在UTF-8-添加字节顺序标记&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; fwrite($ f,pack(“ CCC”,0xef,0xbb,0xbf));&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; fwrite($ f,$ content);&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; fclose($ f);&nbsp;}&nbsp;?>
随时随地看视频慕课网APP
我要回答