Parsing JSON with PHP

Parsing JSON with PHP

  1. Blog
  2. 15 November 2026
  3. 2 min read

Stefan Bogdanescu

Founder & Senior Architect

When you receive a JSON response from an API like Google's Shopping service, the immediate hurdle is often understanding how json_decode() structures that data in PHP. In your specific case, json_decode($data) returns an object containing a single property: items. This property holds an array of product objects. Attempting to iterate directly over $json with foreach($json as $key => $value) simply iterates over the root-level metadata (like kind, etag, totalItems), not the products you actually want to process.

To access the inner data, you must navigate this hierarchy explicitly. The structure is effectively $json->items[0]. However, accessing properties of objects in PHP requires dot notation ($obj->property) or curly braces ($obj['property']). You cannot use standard array syntax like $json[$key] to access the items key because $json is an object, not an associative array.

Navigating the Object Hierarchy

Once you have decoded the JSON, your first step is to isolate the items collection. Since each item in that collection shares a similar structure, you can iterate through them. Within each iteration, you need to dig deeper into the nested product object.

Here is how you would extract the specific fields you mentioned—title, description, brand, and availability:

$json = json_decode($data);

if ($json && isset($json->items)) {
    foreach ($json->items as $item) {
        // Each item has a 'product' object inside it
        $product = $item->product;

        echo "Title: {$product->title}<br>";
        echo "Brand: {$product->brand}<br>";
        echo "Description: {$product->description}<br><hr>";

        // Handling nested arrays like 'inventories'
        foreach ($product->inventories as $inventory) {
            echo "Availability: {$inventory->availability}<br>";
            echo "Price: {$inventory->price} {$inventory->currency}<br>";
        }
    }
} else {
    // Handle cases where the API returns no results or an empty structure
    echo "No items found or invalid JSON.";
}

Dealing with Nested Arrays and Objects

A common pitfall when parsing this specific JSON format is encountering nested structures, such as inventories or images. In your example, each product has a product object containing these arrays. You must ensure your loop logic accounts for the fact that $item is not the full product data but a wrapper around it.

Furthermore, properties like author are themselves objects ($product->author->name). If you

Our network