PHP file_get_contents specific encoding

2019-09-01 16:16发布

i have one special issue with file_get_contents in PHP, here is code:

$html = file_get_contents("http://www.bratm.sk/trochu-harlem-inspiracie-zaslite-nam-svoj-super-harlem-shake-ak-bude-husty-zverejnime-ho");

it gives me something like this

í}KsŰĆŇčÚŽň!Ç& zRŚ|iI[#)öIkI ĆĺăĹŮÝĹÍý_ŐŃâ[EVßîV%Ů˙ëvĎ ř)śG#óčééééÇĚ çáÜöÁÖÉ;¤áˇ,rřĂăçť[DQ5íeaKÓśOśÉ?ě='šL¸ÔöLßä6ľ4mg_!JĂ÷˘Śu:L§án];9ŇÎV+ި1|C

in some pages from this page i can get proper encoding and content with iconv, but here im helpless, how can i fix that? thx

3条回答
三岁会撩人
2楼-- · 2019-09-01 16:41

I think you're looking for something like this

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

$filename = "http://www.bratm.sk/trochu-harlem-inspiracie-zaslite-nam-svoj-super-harlem-    shake-ak-bude-husty-zverejnime-ho";
echo file_get_contents($filename, false, $context);
查看更多
做个烂人
3楼-- · 2019-09-01 16:43

That page is in UTF-8. You need to set the header to match:

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

查看更多
仙女界的扛把子
4楼-- · 2019-09-01 16:47

Use cURL. This function is an alternative to file_get_contents.

function url_get_contents($Url) {
if (!function_exists('curl_init')){
    die('CURL is not installed!');
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $Url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
$data = url_get_contents("http://www.bratm.sk/trochu-harlem-inspiracie-zaslite-nam-svoj-super-harlem-shake-ak-bude-husty-zverejnime-ho/");
print_r($data);
查看更多
登录 后发表回答