PHP: file_get_contents - failed to open stream.

2 posts / 0 new
Last post
PHP: file_get_contents - failed to open stream.


I'm trying to establish a function which calculates the distance in between two locations by geocoding them via your geocode api.

The Link itself, when pasted in the browser seems to be working fine, but using phps function file_get_contents it returns failed to open stream and returns timeout.

Here the code:

function getDistance($addressFrom, $addressTo, $unit = ''){
// Google API key
$apiKey = 'gc5HYKu9JFdc0gkb5X8i0C7m6iFxsvt3';

// Change address format
$formattedAddrFrom = str_replace(' ', '+', $addressFrom);
$formattedAddrTo = str_replace(' ', '+', $addressTo);

// Geocoding API request with start address
$geocodeFrom = file_get_contents(''.$formattedAddrFrom.'&key='.$apiKey);
$outputFrom = json_decode($geocodeFrom);
return $outputFrom->error_message;

// Geocoding API request with end address
$geocodeTo = file_get_contents(''.$formattedAddrTo.'&key='.$apiKey);
$outputTo = json_decode($geocodeTo);
return $outputTo->error_message;

// Get latitude and longitude from the geodata
$latitudeFrom = $outputFrom->results[0]->locations[0]->latLng->lat;
$longitudeFrom = $outputFrom->results[0]->locations[0]->latLng->lng;
$latitudeTo = $outputTo->results[0]->locations[0]->latLng->lat;
$longitudeTo = $outputTo->results[0]->locations[0]->latLng->lng;


And the errors:

Warning: file_get_contents( failed to open stream


Fatal error: Maximum execution time of 120 seconds exceeded in C:\xampp\htdocs\...


I'm relatively new to this topic, the snippet is by

Can anyone see the issue?





Since the request works as
Since the request works as expected in a browser, maybe a user group of PHP experts would be able to help with submitting a request. I worked with PHP for a very short time about 19 years ago so I'm afraid I'll be no help at all.