2

My code is

$url = "URL";
$curl = curl_init();
curl_setopt_array($curl, array(
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => 1
));
$result = curl_exec($curl); 
var_dump($result);
$json = json_decode($result);
print_r($json);

curl_close($curl);

The response from var_dump($result) is -

string(1866) "{"status":true,"result":[{"time":"2016-11-15T19:20:27.000Z"},{"time":"2016-11-15T19:18:15.000Z"},{"time":"2016-11-15T19:15:03.000Z"},

The response I get from print_r($json) is -

stdClass Object
(
    [status] => 1
    [result] => Array
    (
        [0] => stdClass Object
            (
                [time] => 2016-11-15T19:20:27.000Z
            )

        [1] => stdClass Object
            (
                [time] => 2016-11-15T19:18:15.000Z
            )

        [2] => stdClass Object
            (
                [time] => 2016-11-15T19:15:03.000Z
            )   

I need the value of time into some variable.

Something I have done in Javscript is -

var response = JSON.parse(xmlHttpSerie.responseText);
response.forEach(function(items)
{
    currentTime = items.time;
}

Can anyone tell me how do I get the value of time from the response in a variable?

1 Answer 1

1

echo $json['result'][0]['time'];

EDIT after major changes to the original question:

You need to use the second parameter of json_decode() to convert objects to associative arrays. Then you can use foreach() to cycle through the array and print times:

$json = json_decode($result, TRUE);
foreach ($json['result'] as $index => $v) {
  echo $v['time'].'<br>';
}    
Sign up to request clarification or add additional context in comments.

6 Comments

I get this error - PHP Fatal error: Cannot use object of type stdClass as array in /var/www/html/fileName.php on line 45
@SMG: Are you sure you have the line $json = json_decode($result, true); just before the echo?
What is the output of var_dump($result);?
string(1866) "{"status":true,"result":[{"time":"2016-11-15T19:20:27.000Z" - This is the output
Is it because I have more than one instances of time in my response? I edited my code with the exact outputs.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.