加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

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

发布时间:2020-12-13 22:02:08 所属栏目:PHP教程 来源:网络整理
导读:我想从 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%ADfr2=sb-topfr=yf
我想从 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));

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

我将不胜感激任何帮助.

解决方法

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

您可以使用stream_context_create为file_get_contents创建自定义stream context,明确声明您接受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);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读