繁体   English   中英

file_get_contents()将UTF-8转换为ISO-8859-1

[英]file_get_contents() converts UTF-8 to ISO-8859-1

我想从yahoo.com获取搜索结果。

但是 file_get_contents()将UTF-8字符集(charset,雅虎使用的)内容转换为ISO-8859-1。

尝试:

$filename = "http://search.yahoo.com/search;_ylt=A0oG7lpgGp9NTSYAiQBXNyoA?p=naj%C5%A1%C5%A5astnej%C5%A1%C3%AD&fr2=sb-top&fr=yfp-t-701&type_param=&rd=pref";

echo file_get_contents($filename);

脚本为

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

要么

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

要么

$er = mb_convert_encoding($filename , 'UTF-8');

要么

$s2 = iconv("ISO-8859-1","UTF-8",$filename );

要么

echo utf8_encode(file_get_contents($filename));

没有帮助,因为在获取网页内容特殊字符作为šťž被替换为问号???

我将不胜感激任何帮助。

这似乎是一个内容协商问题,因为file_get_contents可能会发送一个只接受ISO 8859-1作为字符编码的请求。

您可以使用stream_context_createfile_get_contents创建自定义流上下文 ,该stream_context_create明确声明您接受UTF-8:

$opts = array('http' => array('header' => 'Accept-Charset: UTF-8, *;q=0'));
$context = stream_context_create($opts);

$filename = "http://search.yahoo.com/search;_ylt=A0oG7lpgGp9NTSYAiQBXNyoA?p=naj%C5%A1%C5%A5astnej%C5%A1%C3%AD&fr2=sb-top&fr=yfp-t-701&type_param=&rd=pref";
echo file_get_contents($filename, false, $context);

的file_get_contents 不应更改字符集。 数据以二进制字符串形式输入。

签出您提供的网址时,这是它提供的标题:

Content-Type: text/html; charset=ISO-8859-1

另外,身体:

<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">

此外,您无法将UTF-8无损转换为ISO-8859-1,并在返回UTF-8时返回字符。 UTF-8 / unicode支持更多字符,因此字符在第一步中丢失。

在浏览器中情况并非如此,因此您可能需要提供正确的Accept-Encoding标头来指示yahoo的系统,您可以接受UTF-8。

对于任何调查此事的人:

我花在编码问题上的时间告诉我,很少有php函数“神奇地”改变了字符串的编码。 (这些罕见的例子之一是:

exec( $command, $output, $returnVal )

另请注意,工作标头集如下:

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

并不是:

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

由于我遇到了与您描述的问题类似的问题,因此足以正确设置标头。

希望这可以帮助!

$s2 = iconv("ISO-8859-1","UTF-8//TRANSLIT//IGNORE",$filename );

改善方案......

function curl($url){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_ENCODING, 1);
    return curl_exec($ch);
    curl_close($ch);
}

echo curl($filename);

暂无
暂无

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

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