Resolve file_get_contents in PHP to get remote page garbled
- 2020-06-19 09:59:24
- OfStack
file_get_contents of PHP gets the content of the remote page, and if it is encoded by gzip, the string returned is the encoded mess
1. Solution: find a function of ungzip to convert
2. Put a prefix on your url and call it this way
$content = file_get_contents("compress.zlib://".$url);
The above code works regardless of whether the page is gzip compressed or not!
Using the curl module can also solve the problem
1. Solution: find a function of ungzip to convert
2. Put a prefix on your url and call it this way
$content = file_get_contents("compress.zlib://".$url);
The above code works regardless of whether the page is gzip compressed or not!
Using the curl module can also solve the problem
function curl_get($url, $gzip=false){
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
if($gzip) curl_setopt($curl, CURLOPT_ENCODING, "gzip"); // Here's the key
$content = curl_exec($curl);
curl_close($curl);
return $content;
}