-2

I am trying to get the contents of a JSON result into php variables. The code I am using is:

$request = json_decode(file_get_contents("https://api.sunrise-sunset.org/json?lat=51.507351&lng=-0.127758&date=today"), true); 

The output of the JSON call looks like this:

array(2) { 
     ["results"]=> array(10) { 
         ["sunrise"]=> string(10) "4:21:35 AM" 
         ["sunset"]=> string(10) "7:32:34 PM" 
         ["solar_noon"]=> string(11) "11:57:04 AM" 
         ["day_length"]=> string(8) "15:10:59"
         ["civil_twilight_begin"]=> string(10) "3:42:08 AM"
         ["civil_twilight_end"]=> string(10) "8:12:01 PM"
         ["nautical_twilight_begin"]=> string(10) "2:49:55 AM" 
         ["nautical_twilight_end"]=> string(10) "9:04:14 PM" 
         ["astronomical_twilight_begin"]=> string(10) "1:41:12 AM" 
         ["astronomical_twilight_end"]=> string(11) "10:12:57 PM" 
      } 
      ["status"]=> string(2) "OK" 
} 

How can I get the "sunrise" time and the "sunset" times into php variables $SunRiseTime and $SunSetTime;

Many thanks in advance for your time.

2
  • echo json_decode($json,true)["results"]["sunrise"]; and echo json_decode($json,true)["results"]["sunset"]; Commented May 6, 2017 at 15:33
  • stackoverflow.com/q/43673876/6521116 Commented May 6, 2017 at 15:39

3 Answers 3

1

Simple and straight.

<?php
ini_set('display_errors', 1);

$json = file_get_contents("https://api.sunrise-sunset.org/json?lat=51.507351&lng=-0.127758&date=today"); 
$array=json_decode($json,true);

echo $SunRiseTime=$array["results"]["sunrise"];
echo $SunSetTime=$array["results"]["sunset"];

Output: 4:21:35 AM 7:32:34 PM

Sign up to request clarification or add additional context in comments.

3 Comments

perfect, thats just what I needed. Many thanks to all that replied.
@DCJones welcome ... :)
I will as soon the system will let me, thanks.
0
$SunRiseTime = $request['results']['sunrise'];
$SunSetTime  = $request['results']['sunset'];

Comments

0

use $$ to define a variable in php dynamic. If your want to static define a variable, directly assign the value to it.

dynamic,

$name = 'SunRise';
$$name = $array["results"]["sunrise"];

static name,

$SunRise = $array["results"]["sunrise"];

3 Comments

Why not just directly use $SunRise?
For this is maybe dynamic. if this is static you're right.
appears to be static

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.