Parsing JSON with PHP

If I was you, I would parse the JSON as an array instead of as an object. This can be done by doing the following:

$json = json_decode($data, true);

By included the second argument in json_decode with a value of true, you get back an array. You can then do something like:

echo '<pre>';
print_r($json);
exit;

This will give you an idea of the array structure of the data and how to access the information you want. For example, to pull the title, brand, and description of each item, you’d do the following:

foreach($json['items'] as $item) {
    echo 'Title: ' . $item['product']['title'] . '<br />';
    echo 'Brand: ' . $item['product']['brand'] . '<br />';
    echo 'Description: ' . $item['product']['description'] . '<br />';
}

To get the availability, again do a dump of the array using print_r() and figure out the best way to access it from the array.

Leave a Comment