Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ludo1960's avatar

Convert JSON string to array

Hi guys,

Consider the following:

$url = "https://someURI";

$response = json_decode(file_get_contents($url));

print_r($response) ;  //nice big string returned 

print_r (explode(" => ",$response)); //nothing returned ???

How do I deal with a big string, can I convert it to an array? Data is structured so:

stdClass Object ( [country] => England [result_count] => 1797 [longitude] => -1.210158 [area_name] => Oxford [listing] => Array ( [0] => stdClass Object ( [country_code] => gb [num_floors] => 0 [image_150_113_url] => https://some.jpg[listing_status] => sale [num_bedrooms] => 6 [location_is_approximate] => 0 [image_50_38_url] => https://another.jpg [latitude] => 51.74293 [furnished_state] => [agent_address] => High Street, Goring, Reading [category] => Residential [property_type] => Detached house [longitude] => -1.313658 [thumbnail_url] => blah blah

If it was an array I could get the keys to see what i'm dealing with, any idea guys?

0 likes
17 replies
ludo1960's avatar

Very quick answer, Array[0] is returned but there are more nested Arrays, how to access those?

hfalucas's avatar

Is everything being converted to an array? Show a small example of the output you are having now as well as what are trying to do and how.

ludo1960's avatar

ok so:

$response = json_decode(file_get_contents($url), true);

print_r(array_keys($response));

gives:

Array ( [0] => country [1] => result_count [2] => longitude [3] => area_name [4] => listing [5] => street [6] => town [7] => latitude [8] => county [9] => bounding_box [10] => postcode )

print_r($response) ;
gives:

Array ( [country] => England [result_count] => 1796 [longitude] => -1.210158 [area_name] => Oxford [listing] => Array ( [0] => Array ( [country_code] => gb [num_floors] => 0 [image_150_113_url] => https://lid.zoocdn.com/150/113/d23e28cf074d77c62ec7151dab09cffa8dbaf210.jpg [listing_status] => sale [num_bedrooms] => 6 [location_is_approximate] => 0 [image_50_38_url] => https://lid.zoocdn.com/50/38/d23e28cf074d77c62ec7151dab09cffa8dbaf210.jpg [latitude] => 51.74293 [furnished_state] => [agent_address] => High Street, Goring, Reading [category] => Residential [property_type] => Detached house [longitude] => -1.313658 [thumbnail_url] => https://lid.zoocdn.com/80/60/d23e28cf074d77c62ec7151dab09cffa8dbaf210.jpg [description] => Nestled in a private corner of exclusive Hid’s Copse Road on the outskirts of Oxford, Water Combe is a brand new property constructed to an extraordinarily high standard with an astonishing attention to detail. The property is full of light and space with most rooms having a double aspect and large windows designed to take advantage of the far reaching and garden views. Bespoke features include a luxurious designer kitchen/breakfast room, generous reception rooms, spacious hallways and landings, an internal green oak frame which adds stunning character, wide oak floors, large bedrooms and fabulous bathrooms with Bateau bath tubs.Set within 1.2 acres, the landscaping has been designed around the Fairy Glen at the bottom of the garden and the Fairy theme continues throughout the house and garden. This enchanting home has had no expense spared to create a unique home for the discerning buyer. Awaiting EPC Rating.Local informationCumnor Hill is a sought after residential area just 1.5 miles from the centre of Oxford. It is well served by communications with access to the A34 and Oxford ring road, connecting to the M4 and M40 motorways, with the regional centres of Newbury and Swindon also within easy reach.Communications by rail are also excellent with fast trains from either Oxford or Didcot to London Paddington taking about 50 and 45 minutes respectively. From the coach station at Gloucester Green there are regular services to London Heathrow and Gatwick airports.Hid’s Copse
hfalucas's avatar

Assign it to a variable and access it like a normal array.

$response = json_decode(file_get_contents($url), true);

$keys = array_keys($response)

$keys[0] // country
$keys[3] // area_name

// or

$response['country'] // England
$response['result_count'] // 1796
ludo1960's avatar

That's fine for items in Array[0] but what about the other nested Arrays? Is there a PHP command to navigate a tree structure of Arrays?

hfalucas's avatar

You can loop through the array or if you are using Laravel there's the array helper data_get (you can use wildcards)

$data = ['products' => ['desk' => ['price' => 100]]];

$price = data_get($data, 'products.desk.price');

// 100
ludo1960's avatar

How do I find all the Key names in a nested Array? $keys = array_keys($response) only returns the keys from Array[0]

hfalucas's avatar

Laravel doesn't have any helper for that so you'll have to write that logic on your own

ludo1960's avatar

found this little beauty:

function array_keys_multi(array $array)
{
    $keys = array();
    foreach ($array as $key => $value) {
        $keys[] = $key;
        if (is_array($array[$key])) {
            $keys = array_merge($keys, array_keys_multi($array[$key]));
        }
    }
    return $keys;
}

but how to use it in my case: ie how to call the function?

hfalucas's avatar

If you want to have functions like that available everyone in your app, the best way is to create a helpers file and autoload it.

// create a helpers.php file under /app for example
function array_keys_multi(array $array)
{
    $keys = array();
    foreach ($array as $key => $value) {
        $keys[] = $key;
        if (is_array($array[$key])) {
            $keys = array_merge($keys, array_keys_multi($array[$key]));
        }
    }
    return $keys;
}

// update your composer.php with:
 "autoload": {
        "psr-4": {...},
        "classmap": [...],
        "files": ["app/helpers.php"] //add this line
 },

// anywhere you need to call the function
array_keys_multi($myArray)

Another option is simply to create a method in the current class and call it

ludo1960's avatar

ok tried that:

$response = json_decode(file_get_contents($url), true);

array_keys_multi($response);

print_r($keys);

but nothing is returned, am I doing it right?

ludo1960's avatar

I thought that was what the function returned? If not what does it return?

hfalucas's avatar

Yes, the function returns the keys, so you need to set a variable hold those values.

$keys = array_keys_multi($response);

print_r($keys);
ludo1960's avatar

yeah I figured that out, and it works a treat, All keys and values are returned, thanks guys!

ludo1960's avatar

The only other thing is how to adjust the function so the output simulates the array structure ie a line break after every sub array? Any ideas?

Please or to participate in this conversation.