在 PHP 中处理 csv 文件时如何指定编码?
<?php
$row = 1;
$handle = fopen ("test.csv","r");
while ($data = fgetcsv ($handle, 1000, ",")) {
$num = count ($data);
print "<p> $num fields in line $row: <br>\n";
$row++;
for ($c=0; $c < $num; $c++) {
print $data[$c] . "<br>\n";
}
}
fclose ($handle);
?>
上面来自php手册,但我没有看到在哪里指定编码(如utf8左右)
<?php
$row = 1;
$handle = fopen ("test.csv","r");
while ($data = fgetcsv ($handle, 1000, ",")) {
$num = count ($data);
print "<p> $num fields in line $row: <br>\n";
$row++;
for ($c=0; $c < $num; $c++) {
print $data[$c] . "<br>\n";
}
}
fclose ($handle);
?>
The above comes from php manual,but I didn't see where to specify the encoding(like utf8 or so)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试更改区域设置。
正如您提供的 手册 中的示例所示:
同一页面上评论建议的方法:
来自
setlocale()
:Try to change the locale.
Like it says below the example in the manual you gave:
Suggested approach by comment on the same page:
From
setlocale()
:其中之一就是 UTF 字节顺序标记 (BOM) 的出现。字节顺序标记的 UTF-8 字符是 U+FEFF,或者更确切地说,三个字节 - 0xef、0xbb 和 0xbf - 位于文本文件的开头。对于 UTF-16,它用于指示字节顺序。对于 UTF-8 来说,这并不是必需的。
所以需要检测这三个字节并去掉BOM。下面是有关如何检测和删除这三个字节的简化示例。
就这样
One such thing is the occurrence of the UTF byte order mark, or BOM. The UTF-8 character for the byte order mark is U+FEFF, or rather three bytes – 0xef, 0xbb and 0xbf – that sits in the beginning of the text file. For UTF-16 it is used to indicate the byte order. For UTF-8 it is not really necessary.
So you need to detect the three bytes and remove the BOM. Below is a simplified example on how to detect and remove the three bytes.
That's all
试试这个:
try this: