-1

I am trying to decode json with PHP but dont know where am i wrong. Here is my code

$rr ='var modelsGlobal = [{"value":"FAFW3801LW","productdetailurl":"/Washers-Dryers/Washers/Front-Load/FAFW3801LW/"}{"value":"FAFW3801LW","productdetailurl":"/Washers-Dryers/Washers/Front-Load/FAFW3801LW/"}]';

$json = json_decode($rr, true);
        foreach($json['modelsGlobal'] as $json){
        $prod_id = $json["value"];
        }

Please help

Harinder
  • 1,257
  • 8
  • 27
  • 54

2 Answers2

4

You are trying to decode (broken) JavaScript, not JSON.

JSON wouldn't include var modelsGlobal = and array members need a , between them.

Run your data through a linter.


After you fix the errors which are preventing the parsing, the JSON doesn't start with an object with a modelsGlobal, so loop over the array in $json directly.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

Your JSON is incorrect. It is not JSON but JavaScript and it lacks a comma to separate the two objects of the array.

If you use PHP 5.3+ use json_last_error to check errors with json_encode/json_decode.

Serty Oan
  • 1,737
  • 12
  • 19