Home > front end >  Get value from Json object (url) in php
Get value from Json object (url) in php

Time:01-31

I have a json i am fetching remotely in php, the Json returned is as follow:

{
   "base_currency_code":"USD",
   "base_currency_name":"United States dollar",
   "amount":"1.0000",
   "updated_date":"2022-01-30",
   "rates":{
      "KWD":{
         "currency_name":"Kuwaiti dinar",
         "rate":"0.3030",
         "rate_for_amount":"0.3030"
      }
   },
   "status":"success"
}

the i try to get the specific value from key : rate :

$url='https://...';
$json = file_get_contents($url);
$obj = json_decode($json,true);
echo $obj['rates']['KWD']['rate'];

but I have no output, when I would like to have 0.3030. Why is this?

CodePudding user response:

test.json

{
   "base_currency_code":"USD",
   "base_currency_name":"United States dollar",
   "amount":"1.0000",
   "updated_date":"2022-01-30",
   "rates":{
      "KWD":{
         "currency_name":"Kuwaiti dinar",
         "rate":"0.3030",
         "rate_for_amount":"0.3030"
      }
   },
   "status":"success"
}

test.php

<?php 
$url='test.json';
$json = file_get_contents($url);
$obj = json_decode($json,true);
echo $obj['rates']['KWD']['rate'];

Result 0.3030

If it is not working, you cannot access the site remotely.

try it and make sure it works

<?php 
$url='https......';
$json = file_get_contents($url);
echo $json;

CodePudding user response:

it looks like your fetch is not working.

because your code works as expected, see here: https://3v4l.org/dnU4j

  •  Tags:  
  • Related