Stupid Dojo
Stupid Dojo

Reputation: 15

json response handling issue

I'm stuck with retrieving json response below is the json output. Your help would be highly appreciated.

{ "productHeader" : { "totalHits" : 684 }, "products" : [ { "name" : "Victoria Hotels", "productImage" : { "url" : "http://hotels.com/hotels/9000000/8640000/8633700/8633672/8633672_20_b.jpg" }, "language" : "en", "description" : "Location. Victoria Hotels is in Foshan (Nanhai) and area attractions include Renshou Temple and New Plaza Stadium. Additional regional attractions include Guangdong Folk Art Museum and Bright Filial Piety Temple.", "identifiers" : { }, "fields" : [ { "name" : "regions2", "value" : "Guangdong" }, 

Please help me to fetch the particular values. For example if I need to fetch the name, image url from the json response.

Upvotes: 0

Views: 46

Answers (2)

Florian
Florian

Reputation: 2874

You can use json_decode to parse a JSON string to an array and access it's values:

// assuming, that $string contains the json response
// second parameter to true, to get an array instead of an object
$data = json_decode( $string, true );
if ( $data ) {
  echo $data['products'][0]['name'];
  // or whatever value
} else {
  echo 'JSON could not be parsed, error: ' . json_last_error();
}

To show all values in the products array, simple loop it:

if ( $data ) {
  foreach($data['products'] as $product){
      echo $product['name'];
  }
  // or whatever value
} else {...

Upvotes: 1

AmBeam
AmBeam

Reputation: 332

If you're going to use PHP to get the values, check this:

$decodedJson = json_decode($json, true);
print_r($decodedJson);

You will get an array, to get image source and other tags you need to do it in a loop or select concrete index like:

echo $decodedJson['productHeader']['products'][0]['productImage']['url'];

In JS you should extract the values the same way.

Upvotes: 0

Related Questions