gpt4 book ai didi

php - 在 PHP 中,当我使用 fwrite 时,我没有得到正确的字符集

转载 作者:行者123 更新时间:2023-12-02 18:20:13 26 4
gpt4 key购买 nike

这是我的代码:

<?php
header("Content-Type: text/html; charset=UTF-8");
header("Content-Type: application/x-javascript; charset=UTF-8");

$fName = "demo.txt";
$str = "óé";
fid = fopen($fName, 'wb') or die("can't open file"); // Open file

fwrite($fid, $str); // Write to file
fclose($fid); // Close file
?>

到屏幕上,输出是:

óéü

当我打开文件时,我得到:

óéü

我尝试使用 fwrite 保存大量数据,但在文件保存时字符编码不正确。

提前致谢。

最佳答案

fwrite 存储二进制字符串。它不进行任何字符集转换。更有可能的是,您的 PHP 脚本的字符集错误,因此原始的 "óéü" 字符串也错误。如果您无法自行调试,请向我们展示 bin2hex($str)bin2hex(file_get_contents('demo.txt'))

有一些通用选项可以解决此类问题:

  • 保存前使用 utf8_encode($str)
  • 首先将 UTF-8 BOM 写入输出文件fwrite($f, "\xEF\xBB\xBF")
  • 使用 iconv() 进行正确转换
  • 或使用 recode L1..UTF8 script.php 调整 php 脚本本身

关于php - 在 PHP 中,当我使用 fwrite 时,我没有得到正确的字符集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4883035/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com