繁体   English   中英

如何使用file_get_contents以正确的utf-8编码获取文件内容?

[英]How to get file content with a proper utf-8 encoding using file_get_contents?

我需要以utf-8编码获取远程文件的内容。 utf-8中的文件。 当我在屏幕上显示该文件时,它具有正确的编码:

http://www.parfumeriafox.sk/source_file.html

(注意ňč字符,例如,这些都可以)。

当我运行此代码时:

<?php

$url = 'http://parfumeriafox.sk/source_file.html';

$csv = file_get_contents_utf8($url);
header('Content-type: text/html; charset=utf-8');
print $csv;

function file_get_contents_utf8($fn) {
  $content = file_get_contents($fn);
  return mb_convert_encoding($content, 'utf-8');
}

(您可以使用http://www.parfumeriafox.sk/encoding.php来运行它),然后我得到问号而不是那些特殊字符。 我对此进行了大量研究,尝试了标准的file_read_contents函数,甚至使用了一些流bla php上下文函数,还尝试了fopen和fread函数以二进制级别读取该文件,似乎没有任何作用。 我已经尝试过,并且不发送标题。 这应该很简单,我在做什么错? 当我使用某种编码检测功能检查该字符串时,它将返回UTF-8

您可以通过打开开发者控制台并查看document.characterSet来查看浏览器确定文档使用的字符集:

> document.characterSet
"windows-1250"

有了这些知识,我们可以要求iconv为我们从“ windows-1250”转换为utf-8:

<?php
$text = file_get_contents("source_file.csv");
$text = iconv("windows-1250", "utf-8", $text);
print($text);

输出是有效的utf-8,并且levanduľa也正确显示。

这个怎么样????

为此,我使用了header('Content-Type: text/plain;; charset=Windows-1250');

佛手柑,citrón,trava,rebarbora,bazalka;levanduľa,škorica,hruška;céderovédrevo,vanilka,pižmo,amberlyn


在此处输入图片说明


该代码对我有用

<?php
header('Content-Type: text/plain;charset=Windows-1250');
echo file_get_contents('http://www.parfumeriafox.sk/source_file.html');
?>


问题不在于file_get_contents()

我将$ data保存到文件中,并且字符正确,但文本编辑器仍未正确编码。 参见下图。

$data = file_get_contents('http://www.parfumeriafox.sk/source_file.html');
file_put_contents('doc.txt',$data);

更新

似乎是一个有问题的字符,如下所示。 在下面的HTML图像上也可以看到它。 渲染为¾

十六进制值为xBE(十进制190)

我尝试了这两个字符集。 两者都不起作用。

header('Content-Type: text/plain; charset=ISO 8859-1');
header('Content-Type: text/plain; charset=ISO 8859-2');



在此处输入图片说明


更新结束


它通过添加不带charset = utf-8的标头来工作。

这两个标头有效

header('Content-Type: text/plain');
header('Content-Type: text/html');

这两个标头不起作用

header('Content-Type: text/plain; charset=utf-8');
header('Content-Type: text/html; charset=utf-8');

此代码已测试并显示所有字符。

<?php
header('Content-Type: text/plain');
echo file_get_contents('http://www.parfumeriafox.sk/source_file.html');
?>

在此处输入图片说明

<?php
header('Content-Type: text/html');
echo file_get_contents('http://www.parfumeriafox.sk/source_file.html');
?>

在此处输入图片说明



这些是带有十六进制值的一些有问题的字符。
这是在记事本中使用UTF-8编码查看的已保存文件。

在此处输入图片说明

根据这些字符集检查十六进制值。

在此处输入图片说明

从上表中,我看到字符集是Latin2。

我去了Wikipedia Windows代码页 ,发现Latin2是Windows-1250


佛手柑,citrón,trava,rebarbora,bazalka;levanduľa,škorica,hruška;céderovédrevo,vanilka,pižmo,amberlyn

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM