0

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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • Use [json_decode](http://php.net/json_decode) to get an array and then just access the keys. – joconja Jun 16 '15 at 10:16
  • In php you can use json_decode to obtain an array structure from a json – Goikiu Jun 16 '15 at 10:16
  • possible duplicate of [Parsing JSON file with PHP](http://stackoverflow.com/questions/4343596/parsing-json-file-with-php) – Robert Jun 16 '15 at 10:19

2 Answers2

1

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 {...
Steve
  • 20,703
  • 5
  • 41
  • 67
Florian
  • 2,796
  • 1
  • 15
  • 25
0

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.

AmBeam
  • 332
  • 1
  • 9