Jump to content

how to echo out a value from json array

Go to solution Solved by Barand,

Recommended Posts

Hello everyone. I'm a self learner that is very new to programming. I'm trying to print out the value of ["mid"]  from a json_decode variable in the code shown below: 

I'm trying to use for each to access the value of "mid'. using foreach function. I know I'm not doing it the right way. please help me or show me an easy was to go around it.

/////the json resopnd form the url is  :


$auth = base64_encode("username:password");
$context = stream_context_create([
    "http" => [
        "header" => "Authorization: Basic $auth"
$homepage = file_get_contents("https://xecdapi.xe.com/v1/convert_from?to=NGN&amount=1.195", false, $context );
$json = json_decode($homepage, TRUE);
foreach ($json as $price){
    echo $price['mid'];



Link to post
Share on other sites
  • Solution

If you

echo '<pre>$json = ', print_r($json, 1), '</pre>';

you get

$json = Array
    [terms] => http://www.xe.com/legal/dfs.php
    [privacy] => http://www.xe.com/privacy.php
    [from] => USD
    [amount] => 1.195
    [timestamp] => 2021-02-09T16:52:00Z
    [to] => Array
            [0] => Array
                    [quotecurrency] => NGN
                    [mid] => 454.6559871014



Then follow the array keys to the value you want


So you need

echo $json['to'][0]['mid'];        // --> 454.6559871014

[edit] Alternatively

foreach ($json['to'] as $price)  {
    printf('%s %0.2f<br>', $price['quotecurrency'], $price['mid'] );        // --> NGN 454.66


Edited by Barand
  • Thanks 1
Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.