JSON data and PHP - php

I am retrieving data via JSON and PHP from a URL.
I am having difficulty breaking the object apart and displaying the data. The PHP code seems to be working until I get to the for loops.
$jsonurl = 'http://myweb/api.php';
$json = file_get_contents($jsonurl);
$json_output = json_decode($json);
foreach ($json_output->Monitoring AS $monitoring) {
foreach ($monitoring->Status AS $Status){
echo $Status->Emailed;
echo $Status->Status;
}
Here is my data structure:
object(stdClass)#12 (1)
{ ["Monitoring"]=> array(10) { [0]=> object(stdClass)#13 (14)
{
["Status"]=> string(30) "HTTP/1.1 302 Moved Temporarily"
["Emailed"]=> string(1) "0" }
[1]=> object(stdClass)#14 (14) {
["Status"]=> string(30) "HTTP/1.1 302 Moved Temporarily"
["Emailed"]=> string(1) "0" }
[2]=> object(stdClass)#15 (14) {
["Status"]=> string(30) "HTTP/1.1 302 Moved Temporarily"
["Emailed"]=> string(1) "0" }
[3]=> object(stdClass)#16 (14) {
["Status"]=> string(30) "HTTP/1.1 302 Moved Temporarily"
["Emailed"]=> string(1) "0" }
} }

According to the data structure you put, you only need one foreach loop like:
$jsonurl = 'http://myweb/api.php';
$json = file_get_contents($jsonurl);
$json_output = json_decode($json);
foreach ($json_output->Monitoring AS $Status) {
echo $Status->Emailed;
echo $Status->Status;
}
in the first foreach loop, the value ($monitoring in your code, $Status in mine as I just renamed it) is not another array that you need to loop over. It would contain a std object with Emailed and Status as keys.

First of all, are you sure your script returns actual JSON string? Did you json_encode it?
Did you compare the 'data structure' of the object before JSON and after decoding? Were there any differences? Maybe it is not at all about the foreach loops and JSON and the problem is instead in your data structure of sorts, which seems to consist of multiple sub-objects.
Alternative is to try and use associative arrays instead of objects in that context by returning json_decode($json,true) and treating it as an array.

At the outset, make sure you turn error reporting on so you can see what exactly is failing.
An improper format passed to json_decode will just return false. It is one of the limitations of PHP's json handling that they are trying to address in the next release by creating a JSONSerializable interface. Make sure the return for decode is an instance of stdClass (or an array if you have passed the option for an associative array), otherwise the loops will never execute at all.

Related

PHP: how can I access JSON object

I'm sending this JSON:
[{"tipo":""},{"activo":""},{"titulo":"Servicoasd B"},{"texto":"asdasdasd"}]
to a php file via post method.
There, i do
$obj = json_decode($_POST['sentJson']);
However, I seem to be unable to access the elements of the JSON.
var_dump(($obj));
Shows the object:
array(4) {
[0]=>
object(stdClass)#2 (1) {
["tipo"]=>
string(0) ""
}
[1]=>
object(stdClass)#3 (1) {
["activo"]=>
string(0) ""
}
[2]=>
object(stdClass)#4 (1) {
["titulo"]=>
string(9) "Servico B"
}
[3]=>
object(stdClass)#5 (1) {
["texto"]=>
string(6) "asdasd"
}
}
But if I try
$obj['texto'];
$obj->{'texto'};
$obj[0]['texto'];
$obj[0];
It shows "undefined index texto" or "trying to get property of non object in" and the last one "Object of class stdClass could not be converted to string in". I'm very new to PHP, but still I can't seem to notice what I'm doing wrong. Any help would be appreciated.
Your JSON is a serialized array of four completely different objects, so when you run json_decode, that's what you get: an array.
If you want to access your objects inside that array, access them like you would any other indexed array:
$list = json_decode(...);
foreach($list as $obj) {
var_dump($obj)
}
Or target them explicitly using plain old numerical access.
$list = json_decode(...);
$last = $list[3];
$text = $last->texto;
But really the question you should be asking is why this is the JSON you get. An array with completely different objects at each position is terrible data, and should be fixed.

PHP cURL API response handling

I have a question regarding the handling of a response from an API using the cURL function from PHP.
If I access the API via cURL I get the following response:
{"status":"ok","meta":{"count":1},"data":{"502268596":{"clan_id":500022074}}}
I transformed this code (named $json) using:
$jsondecoded = json_decode($json,true);
If I var_dump the associative array I now got I receive the following:
array(3) { ["status"]=> string(2) "ok" ["meta"]=> array(1) { ["count"]=> int(1) } ["data"]=> array(1) { [502268596]=> array(1) { ["clan_id"]=> int(500022074) } } }
My Question is: How do I access the field "clan_id"? I'm absolutely lost, because I don't have a real understanding of how arrays work and how I cycle through them.
Your response data is in array format. In this specific case, you can access clan id as follows:
echo $jsondecoded['data'][502268596]['clan_id'];
If you would rather work with objects, you can do so this way:
$jsondecoded = json_decode($json);
echo $jsondecoded->data->{502268596}->clan_id;

Accessing array with nested objects

I have an api wrapper i am using that returns something like this
object(stdClass)#7 (1) {
[0]=>
object(stdClass)#6 (2) {
["contactId"]=>
string(2) "nV"
["email"]=>
string(31) "email#domain.com"
}
}
how do i access the email part with PHP
Cast your API returned data to an array.
For example you are saving API returned data in $result variable. Cast it to an array.
$arrayResult = (array) $result;
echo $arrayResult[0]->email;
Try this.

php, from json decode to individual variables

I am trying to go from a cur request to a page with some info.
I have the curl working but I have trouble going from the decode json to individual php variables. the conten after json_decode is:
object(stdClass)#1 (2) { ["response"]=> object(stdClass)#2 (2) { ["request"]=> string(20) "mailboxes/status/get" ["result"]=> string(1) "0" } ["status"]=> string(7) "success" }
I need the value of result which is 0 here.
Thanks in advance.
$result = $data->response->result;
Assuming the variable $data is where you stored your json_decode. It returns an instance of stdClass, and viewing the vardump, you can see the structure and get the data you want.

Decoding JSON string in PHP which has different headers

I am trying to decode a series of JSON messages
The JSON messgaes are received on an adhoc basis
If the JSON messages were all exactly the same format I would be fine. However they are not.
Here is an example of two different types.
object(stdClass)#11 (1) { ["SF_MSG"]=> object(stdClass)#12 (5) { ["time"]=> string(13) "1407962618000" ["area_id"]=> string(2) "NM" ["address"]=> string(2) "2B" ["msg_type"]=> string(2) "SF" ["data"]=> string(2) "FE" } }
object(stdClass)#13 (1) { ["CA_MSG"]=> object(stdClass)#14 (5) { ["to"]=> string(4) "0360" ["time"]=> string(13) "1407962618000" ["area_id"]=> string(2) "WH" ["msg_type"]=> string(2) "CC" ["descr"]=> string(4) "2S30" } }
One has a header of SF_MSG and the other CC_MSG
My question is "How do I in PHP distinguish between the different headers so I can read them in different ways
So for example echo '$Decodedjson->SF_MSG->time; will echo the time on the first one and
echo $Decodedjson->CC_MSG->to; will echo the to variable. However I need to know whether the header is SF_MSG or a CC_MSG before performing that task.
How do I read that Header title????? ie is it CC_MSG or SF_MSG ......$Decodedjson->?????
Thanks
EDIT
if ($con->hasFrame()){
$msg=$con->readFrame();
foreach (json_decode($msg->body) as $event) {
if(isset($event['SFG_MSG'])) {
$aid=($event->SF_MSG->area_id);
}
elseif(isset($event['CA_MSG'])) {
$aid=($event->CA_MSG->area_id);
}
echo $aid;
json_decode() requires true as the second parameter in order for the resultant object to be an associative array.
foreach (json_decode($msg->body, true) as $event)
once you do this, $event will be an associative array and no longer an object, so you will need to change the rest of your code to access $event as an array instead of an object.
// this won't work
$aid=($event->SF_MSG->area_id);
// change to this
$aid = $event["SF_MSG"]["area_id"];

Categories