php将文件编码转换为utf8编码格式,php-如何以UTF-8格式写入文件?

php-如何以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编码保存文件?

10个解决方案

70 votes

添加BOM:UTF-8

file_put_contents($myFile, "\xEF\xBB\xBF". $content);

user956584 answered 2020-07-06T14:15:43Z

47 votes

file_get_contents / file_put_contents不会神奇地转换编码。

您必须显式转换字符串。 例如mb_convert_encoding()或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'));

Arnaud Le Blanc answered 2020-07-06T14:15:23Z

25 votes

function writeUTF8File($filename,$content) {

$f=fopen($filename,"w");

# Now UTF-8 - Add byte order mark

fwrite($f, pack("CCC",0xef,0xbb,0xbf));

fwrite($f,$content);

fclose($f);

}

?>

Alaa answered 2020-07-06T14:16:00Z

5 votes

Iconv进行救援。

Dennis Kreminsky answered 2020-07-06T14:16:22Z

3 votes

在Unix / Linux上,可以使用一个简单的shell命令来转换给定目录中的所有文件:

recode L1..UTF8 dir/*

也可以通过PHP exec()启动。

mario answered 2020-07-06T14:16:46Z

1 votes

//add BOM to fix UTF-8 in Excel

fputs($fp, $bom =( chr(0xEF) . chr(0xBB) . chr(0xBF) ));

我从酷那里得到这条线

Du Peng answered 2020-07-06T14:17:06Z

0 votes

如果要递归使用重新编码并过滤类型,请尝试以下操作:

find . -name "*.html" -exec recode L1..UTF8 {} \;

Aitor answered 2020-07-06T14:17:27Z

0 votes

这对我有用。 :)

$f=fopen($filename,"w");

# Now UTF-8 - Add byte order mark

fwrite($f, pack("CCC",0xef,0xbb,0xbf));

fwrite($f,$content);

fclose($f);

Atul.Bajare answered 2020-07-06T14:17:46Z

-1 votes

我将所有内容放在一起,并获得了将ANSI文本文件转换为“ UTF-8 No Mark”的简单方法:

function filesToUTF8($searchdir,$convdir,$filetypes) {

$get_files = glob($searchdir.'*{'.$filetypes.'}', GLOB_BRACE);

foreach($get_files as $file) {

$expl_path = explode('/',$file);

$filename = end($expl_path);

$get_file_content = file_get_contents($file);

$new_file_content = iconv(mb_detect_encoding($get_file_content, mb_detect_order(), true), "UTF-8", $get_file_content);

$put_new_file = file_put_contents($convdir.$filename,$new_file_content);

}

}

用法:filesToUTF8('C:/ Temp /','C:/ Temp / conv_files /','php,txt');

Le Inc answered 2020-07-06T14:18:11Z

-6 votes

在Windows笔记本中打开文件

将编码更改为UTF-8编码

保存文件

再试一次! :O)

Kjell E. Svendsen answered 2020-07-06T14:18:45Z

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值