PHP file_get_contents specific encoding

2019-09-01 16:29发布

问题:

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

回答1:

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);


回答2:

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

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



回答3:

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);