json_decode() not working

Question

I have a json file on one of my websites’ server (we’ll call that site 1) that includes a list of states and territories.

I am trying to pull the info into a different site and display the list.

The json file on site 1 includes the following:

[
    {
        "name": "Alabama",
        "abbreviation": "AL"
    },
    {
        "name": "Alaska",
        "abbreviation": "AK"
    },
    {
        "name": "Arizona",
        "abbreviation": "AZ"
    }
]

The php on site 2 is written as follows:

<div><?php getStates(true); ?></div>

<?php
function getStates($br = null){
    // read json file
    $url = 'https://site1.com/states_and_territories_2.json';
    $json = file_get_contents($url);
    
    // convert json object to php associative array
    $data = json_decode($json, true);
    
    // check if we want to break each line
    $br = '';
    if ($br != null){
        $br = '<br>';
    }
    
    print_r($data);
    
    // loop through the array
    foreach ($data as $key => $state) {
        // get the state information
        echo $state['name'] . $br;
    }
}
?>

If I print_r($json), the array shows up just fine with all of my states, but if I print_($data) nothing shows up.

I have also tried skipping the json_decode() and using $json instead of $data in the foreach(), but I’m not getting anything. Maybe I’m not getting the array properly?

0
Mr Gandy 1 month 0 Answers 13 views 0

Leave an answer