Search code examples
phpjsonserver-side

PHP: Accessing dictionaries from a JSON string


I'm writing a simple PHP script that makes an API call that returns JSON. However, I'm having trouble figuring out how to take that JSON string, convert it into a dictionary, and access nested dictionaries/data within it.

Here's what I have so far:

<?php
$id = $_REQUEST['id'];

$url = http://exampleURLThatReturnsJSONString.com
$rawData = file_get_contents($url);

I've read that you should use something like $decodedData = json_decode($rawData) , but I'm not sure what to do next, especially if I want to access nested dictionaries with a key like Schedule.

Any help would be greatly appreciated, thanks!


Solution

  • You can just access the decoded data like this:

    echo $decodedData['key'];
    

    This wil echo the value of the item in the dictionary with key 'key'. Nested values can be accessed like this:

    echo $decodedData['key1']['key2']['...'];
    

    You can always use var_dump to show what's inside the result. Also, read the documentation on json_decode for more information.