Reputation: 328
I have a json feed in a URL that contains following data.
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">
[{"ID":1123,"OrderNumber":"1394","ProjectType":"Postcard","Template":"WtlossStudy solo","TemplateURL":"someone.biz/Home/ShowTemplate/283","ShipDate":"2/28/2015","InHomeDate":"3/2/2015","Quantity":"10,000","Price":"$3,000","CallTracking":"0"},{"ID":1123,"OrderNumber":"1413","ProjectType":"Postcard","Template":"WtlossStudy solo","TemplateURL":"","ShipDate":"3/30/2015","InHomeDate":"3/31/2015","Quantity":"5,000","Price":"$1,500","CallTracking":"0"},{"ID":1123,"OrderNumber":"1413","ProjectType":"Postcard","Template":"WtlossStudy solo","TemplateURL":"","ShipDate":"4/13/2015","InHomeDate":"4/14/2015","Quantity":"5,000","Price":"$1,500","CallTracking":"0"}]
</string>
I need to get it and parse it thorough php. But it is giving invalid foreach error with the following code. Can anyone help me on how to show in correctly.
$json = file_get_contents('http://someurl.biz/api/api/1123');
$obj = json_decode($json, true);
foreach($obj as $ob) {
echo $ob->ID;
}
Upvotes: 2
Views: 245
Reputation: 1219
This works.
As your JSON has become an associative array, you have to make 2 foreach.
Bottom foreach parses each "object" content
$data = json_decode('[{"ID":1123,"OrderNumber":"1394","ProjectType":"Postcard","Template":"WtlossStudy solo","TemplateURL":"someone.biz/Home/ShowTemplate/283","ShipDate":"2/28/2015","InHomeDate":"3/2/2015","Quantity":"10,000","Price":"$3,000","CallTracking":"0"},{"ID":1123,"OrderNumber":"1413","ProjectType":"Postcard","Template":"WtlossStudy solo","TemplateURL":"","ShipDate":"3/30/2015","InHomeDate":"3/31/2015","Quantity":"5,000","Price":"$1,500","CallTracking":"0"},{"ID":1123,"OrderNumber":"1413","ProjectType":"Postcard","Template":"WtlossStudy solo","TemplateURL":"","ShipDate":"4/13/2015","InHomeDate":"4/14/2015","Quantity":"5,000","Price":"$1,500","CallTracking":"0"}]');
foreach($data as $obj) {
foreach($obj as $key=>$val) {
echo $key."->".$val." | ";
}
}
Yes it is simpler with JS. But php "json" is not a JS object, it is an array of associative arrays.
Upvotes: 1
Reputation: 21437
Try as
$json = file_get_contents('http://superiorpostcards.biz/api/api/1123');
$obj = json_decode($json, true);
$array = json_decode($obj, true);
foreach($array as $value){
echo $value['ID'];
}
Upvotes: 4
Reputation: 1219
$my_array_for_parsing = json_decode(/** put the json here */);
this gives you the JSon as php associative array.
$my_array_for_parsing = json_decode($json);
foreach ($my_array_for_parsing as $name => $value) {
// This will loop three times:
// $name = a
// $name = b
// $name = c
// ...with $value as the value of that property
}
Upvotes: 0
Reputation: 5971
If second parameter of json_decode is set to true
, your json
will be transformed in associative array instead of object. Try this:
$obj = json_decode($json, false);
foreach($obj as $ob) {
echo $ob->ID;
}
Upvotes: 0