Issue
I'm trying to get JSON from a URL using the codes below. I always get the errors below.
<?php
$url = ...;
$json = file_get_contents($url);
$dados = json_decode($json, true);
echo "<pre>";
print_r($dados);
?>
Error:
Warning: file_get_contents(https://www.car.gov.br/publico/imoveis/getImovel?lat=-2.449376438504347&lng=-49.04754638759188): Failed to open stream: Redirection limit reached, aborting in ... on line 5
Another code used:
<?php
$url = ...;
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,$url);
$dados = curl_exec($ch);
curl_close($ch);
echo "<pre>";
var_dump(json_decode($dados, true));
?>
Response:
NULL
When using the same code, with another URL, such as:
$url = 'http://api.ipstack.com/177.194.116.144?access_key=65a2a7545d3ea66448ca270dad2dc789'
the feedback works correctly.
Can you help me?
Regards, Diego
Solution
The following seems to work
Using curl:
<?php
$url = 'https://www.car.gov.br/publico/imoveis/getImovel?lat=-2.449376438504347&lng=-49.04754638759188';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:90.0) Gecko/20100101 Firefox/90.0',
'Accept-Encoding: gzip, deflate',
'Accept-Language: en-US,en;q=0.5',
'Accept-Encoding: gzip, deflate, br',
'Connection: keep-alive',
'Cookie: PLAY_SESSION=8c1bbeb68ce32508d4f7ef0003aa61712eb9a12c-___ID=6e7f9897-25b8-49bf-9b7b-974d76f0cc7f; BIGipServerpool_car_https=1681002668.47873.0000; TSb0b96d3e027=08f250eeb3ab2000fa851676d8c0aafe8c0ee0dbbae1a0b5d329a962f73f7693776786518e21bc5608aead07e0113000cea9a18e252ae4845188f4c7c7a8432eebbd8d46f8dd8ddadfc873935b69ea08f6280aee6e084adc65f9193780ad34e3; TS570bd070029=08f250eeb3ab2800fe23562db9686a4e0156e1ac772b60e389613e4652d1c435d0008193c7ae5d55de82b5e4b6ad8d23',
'Upgrade-Insecure-Requests: 1',
'Sec-Fetch-Dest: document',
'Sec-Fetch-Mode: navigate',
'Sec-Fetch-Site: none',
'Sec-Fetch-User: ?1',
'Pragma: no-cache',
'Cache-Control: no-cache',
));
curl_setopt($ch, CURLOPT_VERBOSE, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$dados = curl_exec($ch);
$error = curl_error($ch);
?>
Response:
{"type":"FeatureCollection","crs":{"type":"name","properties":{"name":null}},"features":[{"type":"Feature","geometry":{"type":"MultiPolygon","coordinates":[[[[-49.0527,-2.4519],[-49.0533,-2.4551],[-49.0373,-2.4524],[-49.0367,-2.445],[-49.0517,-2.4478],[-49.0527,-2.4519]]]]},"properties":{"id":"ptS9jr7pPn+kAaDdfHlORQ==","codigo":"PA-1504703-73C3A10E7D0A4E1D8E207BD30890C7CD","area":137.3599,"status":"AT","tipo":"IRU","municipio":"Moju","categoria":"IMOVEL"},"id":"ptS9jr7pPn+kAaDdfHlORQ=="}]}
Without the proper headers the server responds with an empty body. So make sure you set them before making a request.
Answered By - Andreas