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;
}
?>
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;