-1

The following chunk of data is produced by a webpage along with other html data;

"search":{"searchResults":{"results":[

{"id":"123","name":"ABC","rating":{"average":0,"count":2,"__typename":"Rating"},"category":"AAA/Cars","__typename":"ProductQuery"},

{"id":"456","name":"DEF","rating":{"average":5,"count":8,"__typename":"Rating"},"category":"BBB/Bikes","__typename":"ProductQuery"}

{"id": //and so on//
"}

]}}

How to extract multiple variables from this string like data like "id", "rating" etc., to be able to print it on another php page?

AFV
  • 51
  • 6

1 Answers1

0

You can use json_decode to convert JSON to the array and then iterate through the array

$json = '{
"search":
 {
 "searchResults":
 {
    "results":[
            {"id":"123","name":"ABC","rating":{"average":0,"count":2,"__typename":"Rating"},"category":"AAA/Cars","__typename":"ProductQuery"},
            {"id":"456","name":"DEF","rating":{"average":5,"count":8,"__typename":"Rating"},"category":"BBB/Bikes","__typename":"ProductQuery"}
    ]
  }
 }
}';
$jsonToArray = json_decode($json,true);
foreach($jsonToArray['search']['searchResults']['results'] as $v){
   echo $v['id'];
  print_r($v['rating']);echo '<br/>';
}
Rakesh Jakhar
  • 6,380
  • 2
  • 11
  • 20