0

I have this following php file that is supposed to loop through a json array and print the necessary information. But I am getting an error in browser which i don't know why it is shown."( ! ) Parse error: syntax error, unexpected 'foreach' (T_FOREACH) in C:\wamp\www\bootstrap-dist\jsonpost.php on line 15". Can someone help me to solve this.

<?php
 $jArray ='{ "books":[{"id":"01",
                       "language": "Java",
                       "edition": "third",
                       "author": "Herbert Schildt"
                        },
                        {
                       "id":"07",
                       "language": "C++",
                       "edition": "second"
                       "author": "E.Balagurusamy"
                        }]
                    }'

    foreach ($jArray as $obj) { // error in this line
                 $ProductName = $obj['edition'];   
                 $ProductQuantity= $obj['language'];
                 echo   $ProductName+" "+$ProductQuantity;
             }

?>
1
  • Please use something like JSONLint to validate your json strings. Commented Jun 29, 2014 at 12:38

1 Answer 1

3

First of all, the syntax error is because you forgot a semicolon after the JSON variable.

 ... 
        "E.Balagurusamy"
    }]
}'; // <-- there 

And to parse it; use json_decode.

$parsed = json_decode($jArray, true);
foreach ($parsed['books'] as $obj) {
    // ... 

EDIT: Added , true to the json_decode, and also, your JSON has a syntax error.

"edition": "second", /* NOTE THE COMMA HERE */
"author": "E.Balagurusamy"

EDIT 2: Concatenating strings with + leads to 0. Use ..

echo $ProductName." ".$ProductQuantity;
Sign up to request clarification or add additional context in comments.

1 Comment

even then i get this"Warning: Invalid argument supplied for foreach() in C:\wamp\www\bootstrap-dist\jsonpost.php on line 17" error

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.