PHP Convert string response to an Array from an API - php

I have the following value which is returned via API :
[{"message":"No transactions found"}]
this information comes back as a string and I would like to convert it to a JSON or an array.
I have the following two options :
$decoded_msg = json_decode($mpesa_offline_status,TRUE);
echo $decoded_msg['message'];
which return a warning message : Message: Illegal string offset 'message' and this option also:
$decoded_msg = json_decode($mpesa_offline_status,TRUE);
echo $decoded_msg->message;
and I get the following error :
Message: Trying to get property 'message' of non-object
how can I approach this?

You have an array of messages, so you cannot access 'message' at the top level.
$mpesa_offline_status = '[{"message":"No transactions found"}]';
$decoded_msg = json_decode($mpesa_offline_status, true);
var_dump($decoded_msg[0]['message']);
you have to access a valid index. Same with that:
$mpesa_offline_status = '[{"message":"No transactions found"}]';
$decoded_msg = json_decode($mpesa_offline_status, false);
var_dump($decoded_msg[0]->message);

Having [] with this API response means, when you use json_decode() this will generate a multi dimensional array, here [] will be converted into 0 index and message will be associated with 0 index something like:
Array
(
[0] => Array
(
[message] => No transactions found
)
)
For this if you want to access message index which inside the 0 index, you can access as like:
<?
$string = '[{"message":"No transactions found"}]';
$decode = json_decode($string,true);
echo $decode[0]['message']; // No transactions found
?>
Side Note:
Message: Illegal string offset 'message' error doesn't mean, to switch on to property instead of array, this message means, you are trying to access a string value which is an array.

Related

getting values out of json array in codeigniter

Hi am having a little from with json array. when i try to get the values out of json array.
Controller
$data['payment'] = $this->admin->get_payment_settings();
$value = $data['payment'][0]->json;
echo $value['username'];
Hi am having a json array in database. using my controller i am getting the filed json. When i do a var_dump($value) array look like this
{"username":"foodi1.lch.co","password":"FBUEWQH6X4D","signature":"AFcWxV21C7fd0v3bZnWKgr9on9AmTuhyd4MVq","currency":"CAD"}
i want to get each value out of this array.
echo $value['username'];
echo $value['password'];
When i try to do this i get the error
A PHP Error was encountered
Severity: Warning
Message: Illegal string offset 'username'
Filename: controllers/administrator.php
Line Number: 620
Can some one help me to get the values out of json array. tnx..
You need to decode the string to a valid array, use json_decode as follows:
$json = json_decode($value, true);
echo $json['username'];
It seems your $data['payment'][0] is json string.So you need to decode it.
Try this way
$value=json_decode($data['payment'][0]->json,true);//second parameter true will return as array.
echo $value['username'];

Accessing Object Properties returned from ASP.net

I'm working on my first from-scratch back end project. Forgive my ignorance.
I have a page that's filled by data returned from an ASP.net API. I'm connecting to the API successfully using SoapClient, but I'm unable to successfully parse the results.
How can I echo Status in the object below?
The returned object is:
stdClass Object(
[LoginResult] => {
"Result":{
"Status":"FAILED",
"Message":"Access Denied"},
"SessionToken":""
}
)
My code is:
$loginResult->Result;
The error I receive is:
Undefined property: stdClass::$Result.
If $loginResult is the variable of the returned result then it is an object with a property LoginResult that contains a JSON encoded object. Once decoded as an array, it has a Result key array containing the keys Status and Message:
$array = json_decode($loginResult->LoginResult, true);
echo $array['Result']['Status'];
If you don't pass true to json_decode then you get a decoded object containing another object and would use:
$object = json_decode($loginResult->LoginResult);
echo $object->Result->Status;
In PHP >= 5.4.0 you should be able to do:
echo json_decode($loginResult->LoginResult, true)['Result']['Status'];
// or
echo json_decode($loginResult->LoginResult)->Result->Status;

PHP: Illegal string offset

I know there already are questions like this, but It didn't help me.
I get the follow error on my site:
Warning: Illegal string offset 'networkConnections' in
/var/www/bitmsg/templates/header.php on line 25 {
The line is
<?= $bmstatus["networkConnections"] ?> p2p nodes
if I print_r $bmstatus, then I get:
{
"numberOfBroadcastsProcessed": 2308,
"networkStatus": "connectedAndReceivingIncomingConnections",
"softwareName": "PyBitmessage",
"softwareVersion": "0.4.1",
"networkConnections": 52,
"numberOfMessagesProcessed": 22888,
"numberOfPubkeysProcessed": 8115
}
How to I fetch the information from this array?
I've tried both $bmstatus['networkConnections'] and $bmstatus->networkConnections
but both is returning that error?
$bmstatus contains a JSON string. You have to decode it first to be able to extract the required information out of it. For this purpose, you can use the built-in function json_decode() (with the second parameter set as TRUE to get an associative array, instead of an object):
$json = json_decode($bmstatus, true);
echo $json['networkConnections'];
It's a json string. You need to decode your json response using json_decode with second parameter true to get as an associative array.
$bmstatusArray = json_decode($bmstatus,true);
echo $bmstatusArray["networkConnections"];

PHP json_decode thrown an error for validate json string

I have following error
Notice: Trying to get property of non-object in action.php
while posted json has validated (by jsonLint.com validation).
Here is my json string:
[
{
"eTGid": "1",
"eTid": "34",
"evrakGelisTarihi": "12/12/2013",
"evrakKonu": "Sertifika denemesi",
"evrakKurumID": "1047",
"evrakCikisTarihi": "13/12/2013",
"evrakCikisSayisi": "313213213213",
"aciklamaBolumu": "açıklayıcı notlar",
"gelenEvrakTarihi": "30/12/2013",
"gelenEvrakSayisi": "3132321",
"gelenEvrakEtakipNo": "987654",
"bagliIlaclar": "[\"0\",\"[{\\\"ilacID\\\":\\\"744\\\",\\\"ilacPN\\\":\\\"asdasd2132\\\",\\\"ilacSKT\\\":\\\"12/12/2013\\\"}]\"]",
"bagliFirmalar": "[\"0\",\"[{\\\"firmaID\\\":\\\"1047\\\"}]\"]",
"": "[\"0\",\"[{\\\"bankaID\\\":\\\"5\\\",\\\"makbuzNO\\\":\\\"asdasda\\\",\\\"makbuzTARIHI\\\":\\\"12/12/2013\\\",\\\"ihracaatYapilacakUlkeID\\\":\\\"2\\\",\\\"ilacIhracADI\\\":\\\"ABFADER\\\",\\\"makbuzTUTAR\\\":\\\"202,06\\\",\\\"makbuzTipDetayDEGERİ\\\":\\\"10\\\"}]\",\"[{\\\"bankaID\\\":\\\"5\\\",\\\"makbuzNO\\\":\\\"ASDAWW\\\",\\\"makbuzTARIHI\\\":\\\"12/12/2013\\\",\\\"ihracaatYapilacakUlkeID\\\":\\\"191\\\",\\\"ilacIhracADI\\\":\\\"ABFADEX\\\",\\\"makbuzTUTAR\\\":\\\"202,06\\\",\\\"makbuzTipDetayDEGERİ\\\":\\\"9\\\"}]\"]",
"bagliMakbuzlar": "[\"0\",\"987654»12/12/2013»3213213\"]",
"kurumIcimi": "hayir"
}
]
and my php code is:
$gelenJsonVerisi = $_POST['yeniEvrak'];
echo($gelenJsonVerisi);
$yeniEvrakObj = json_decode($gelenJsonVerisi);
exit($yeniEvrakObj->{'eTGid'});
Where did I go wrong?
After suggestions:
My Json string has arrived to the serverside (php) as an array (between brackets).
Array has only one element (member) that it is our json string (object)
Handle the arrays first element and assign it to a php object and deal with it.
$gelenJsonVerisi = $_POST['yeniEvrak'];
$yeniEvrakObjArray = json_decode($gelenJsonVerisi,TRUE);
$yeniEvrakObj = $yeniEvrakObjArray[0];
exit($yeniEvrakObj['eTGid']); // one of sample value
Thank you
The JSON string shows an array, that contains a single object. access the data like so:
$yeniEvrakObj = json_decode($gelenJsonVerisi);
echo $yeniEvrakObj[0]->eTGid;
If you're sure there's but 1 object inside that array, you could try:
$yeniEvrakObj = json_decode(
substr($gelenJsonVerisi,1,-1)
);
Which chops off the leading and terminating brackets. This implies no leading of trailing whitespace, so trim the string first.
check codepad. As you can see, the json_decode call returns the data as an array containing an object:
Array
(
[0] => stdClass Object
(
[eTGid] => 1
[eTid] => 34
[evrakGelisTarihi] => 12/12/2013
[evrakKonu] => Sertifika denemesi
[evrakKurumID] => 1047
[evrakCikisTarihi] => 13/12/2013
[evrakCikisSayisi] => 313213213213
)
)
It's not json_decode throwing the error, it's when you try to access the resulting array. Yes, that's right, array. Your JSON value is this:
[ { ... } ]
^ array ^
So you need to access the result like:
$yeniEvrakObj[0]->eTGid
$gelenJsonVerisi = $_POST['yeniEvrak'];
echo($gelenJsonVerisi);
$yeniEvrakObj = json_decode($gelenJsonVerisi);
exit($yeniEvrakObj[0]->eTGid);
The problem is the way you're trying to access to the decoded object, as it is inside an array.
Your code should be:
$gelenJsonVerisi = $_POST['yeniEvrak'];
echo($gelenJsonVerisi);
$yeniEvrakObj = json_decode($gelenJsonVerisi);
exit($yeniEvrakObj[0]->eTGid);
Edit: Thanks for the comments on this answer that made me see I was mistaken

Can't get value from array

I'm trying to output the value of the email value of an array, but have problems doing so.
The array is based on json_decode()
This is the error I receive
Fatal error: Cannot use object of type stdClass as array in /home/.... line 57
JSON (value of: $this->bck_content)
{"email":"test#email.com","membership_id":"0","fname":"Kenneth","lname":"Poulsen","userlevel":"1","created":"2012-04-23 10:57:45","lastlogin":"2012-04-23 10:58:52","active":"y"}
My code
# Display requested user details
$details_array = json_decode($this->bck_content);
$value = $details_array['email'];
print $value;
You need to use the second argument to json_decode to force array structures on JS objects.
json_decode($this->bck_content, true);
This will make sure all JS objects in the json are decoded as associative arrays instead of PHP StdObjects.
Of course that is assuming you want to use array notation to access them. If you're fine with using object notation then you can just use:
$value = $details_array->email;
try this one
$value = $details_array->email;
or
json_decode($json, true);
or
$details_array = (array)json_decode($json);
what have you done wrong is writen in error description

Categories