-1

This question have been asked many times before but none of the solution seems to works. I want to return JSON data from this url using file_get_contents() but it returning JSON data in raw format (string).

Here is my code:

$data = file_get_contents('https://dev.virtualearth.net/REST/v1/Routes/DistanceMatrix?origins=27.696694861033567,83.46625594498187&destinations=28.233514383842977,83.98651076641227&travelMode=driving&key=bingmaps_api_key&distanceUnit=km');
dd($data);

I have tried using curl but result is same it also return JSON data in raw format (string)

$url = 'https://dev.virtualearth.net/REST/v1/Routes/DistanceMatrix?origins=27.696694861033567,83.46625594498187&destinations=28.233514383842977,83.98651076641227&travelMode=driving&key=ingmaps_api_key&distanceUnit=km';
if (!function_exists('curl_init')) {
    die('The cURL library 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);
dd($output);

Output I want Produced output

Output it gives Required output

Milan Tarami
  • 70
  • 1
  • 8
  • 1
    The question linked as dupicate is not what he was asking for I guess. You're rather looking for the `application/json` header. See: https://stackoverflow.com/questions/4064444/returning-json-from-a-php-script - also, you should remove your API keys. – maio290 Nov 12 '18 at 14:17
  • `dd()` is Laravel's debug output function, right? Then yes, it'll just show the literal string as is. Usually you'd decode the JSON, and do something with it. If this script is just about playback, then an `echo` and the right MIME type would make your browser JSON prettifier engage (if this is what you want, then it's perhaps worth mentioning). – mario Nov 12 '18 at 14:20
  • i will disable this key after a solution – Milan Tarami Nov 12 '18 at 14:23
  • when i do json_decode() it gives me error Call to undefined function GuzzleHttp\json_decode() – Milan Tarami Nov 12 '18 at 14:28

1 Answers1

1

JSON is nothing but a string. file_get_contents or cURL will always return string, you have to decode the string using json_decode method which should give you the JSON object.

AppDevD
  • 143
  • 5
  • when i do json_decode() it gives me error Call to undefined function GuzzleHttp\json_decode() – Milan Tarami Nov 12 '18 at 14:28
  • Looks like you don't have json extension enabled in your php configuration. you should install ext-json and enable it. – AppDevD Nov 12 '18 at 14:30