PHP json_decode not working - displays NULL output - php

I'm trying to use JSON decode to retrieve some information but it's not working, it's just showing the data as null when I use var_dump
Here's the JSON formatted data passed in the URL
orderSummary={"orderInfo":[{"itemNumber":"1","quantity":"3","price":"5.99","productName":"Item_B"}]}
When I simply echo the un-decoded string I get the following
echo $_GET['orderSummary'];
//displays the following
{\"orderInfo\":[{\"itemNumber\":\"1\",\"quantity\":\"3\",\"price\":\"5.99\",\"productName\":\"Item_B\"}]}
However, when I try to decode it the result is null
$order = $_GET['orderSummary'];
$data = json_decode($order,true);
echo "<PRE>";
var_dump($data); die();
//displays the following
<PRE>NULL
Is it not properly formatted?

Run the input string through stripslashes() first.
$input = '{\"orderInfo\":[{\"itemNumber\":\"1\",\"quantity\":\"3\",\"price\":\"5.99\",\"productName\":\"Item_B\"}]}';
print_r(json_decode(stripslashes($input)));
Output
stdClass Object
(
[orderInfo] => Array
(
[0] => stdClass Object
(
[itemNumber] => 1
[quantity] => 3
[price] => 5.99
[productName] => Item_B
)
)
)
Demo
Alternatively
Turn off magic_quotes_gpc. Considering that it has been deprecated (and removed in 5.4), this the better option.

Related

Trying to extract value from Soap XML output

I'm using PHP SoapClient to call a SOAP service.
I'm using the following code to return the below view
$response = $client->Get($request);
echo '<pre>';
print_r($response);
echo '</pre>';
echo '<hr>';
Here's the response
stdClass Object
(
[TransactionID] => 17ACE7B75CB6SDBX
[ResponseType] => SYNC
[Parameters] => stdClass Object
(
[Param] => stdClass Object
(
[_] => SANDBOX20101001123321125.168.214.72125.168.253.29912003D60E04CC4C1F8
[id] => SessionLogRecord
)
)
)
Here is , showing the elements within it that I want to extract the values of
<onlinesessionrecord><serviceid>SANDBOX</serviceid><datetime>20101001123321</datetime><ipaddress>125.168.214.72</ipaddress><nasipaddress>125.168.253.2</nasipaddress><nasport>9912</nasport><sessionid>003D60E04CC4C1F8</sessionid></onlinesessionrecord>
For example, I am trying to extract from above
I have tried to display it using the following, but I get an error "Attempt to read property "onlinesessionrecord" on string"
$data = $response->Parameters->Param->_->onlinesessionrecord->ipaddress;
print_r($data);
If anyone knows what I'm doing wrong, your advice would be appreciated.
I am sure this is very simple, I just seem to struggle with xml.
--- Next Day, further findings after help from comments ---
So, thanks to the comments below, I have now go to this point. If I use the below:-
$data = simplexml_load_string($response->Parameters->Param->_);
$out = $data->IPAddress; // same if I do the following $data[0]->IPAddress;
print_r($out);
I get this:-
SimpleXMLElement Object ( [0] => 125.168.214.72 ) if I do the below.
But I just want to extract the IPAddress value and assign it to a variable. I have tried 2 ways
$out = $data->IPAddress;
and
$out = $data[0]->IPAddress;
Both give the same output, I just want to actual IPAddress and assign it to a variable.

Trying to get property of non-object in json_decode

i am new to JSON i have a json object retrieved from the database in the form of
Array
(
[0] => stdClass Object
(
[id] => 1
[data] => {"vehicle":[{"year":"2000","make":"Ac","model":"Aceca","acquired_year":"2016","acquired_month":"2","use":"Business","distance_driven_to_work_or_school":"2","distance_driven_manually":"10000"}],"first_name":"ADAS","last_name":"DSADSADA","email":"asddsa#sda.com","phone":"dsasasa","postal_code":"","drivers":[{"name":"ssada","birth_year":"2016","birth_month":"2","birth_day":"2","gender":"female","martial_status":"Single","license_number_provided":"yes","license_number":"asddasdas","license_type":"","training_completed":"","years_been_listed_on_auto_policy_in_north_america":"No Previous Experience","license_suspensions":"","accidents":"Select","convictions":"Select","cancellation_reason":"","cancellation_year":"","cancellation_month":"","cancellation_day":""}],"considering_renters_to_reduce_rate":"yes","install_winter_tires":"no","park_in_private_driveway":"yes","willing_to_install_device":"no","years_insured_with_current_company":"4 Years","how_heard_about_us":"asdaa"}
[date] => 2017-11-20 18:17:52
[status] => 0
)
)
now when i try to use json_decode to convert it into an array i am getting Trying to get property of non-object here's my code
<?php
echo "<pre>";
print_r($quotes); //works fine uptil here
$data = json_decode($quotes->data,true);//the error line
echo "<pre>";
print_r($data);
?>
i tried it a couple of ways but it is not working i tried some other solutions as well stil ending up getting errors any help?
It is because $quotes is an array of objects. Try $quotes[0]->data, e.g.:
$data = json_decode($quotes[0]->data,true);
// ------------------------^^^
You're receiving an array containing objects from the database. You're almost there but instead of
$data = json_decode($quotes->data,true);
You should use
$data = json_decode($quotes[0]->data,true);

Can't extract data from Json

I can't extract data from json that I got from an api.
I tried for hours, tried all kinds of formats. Read Stackoverflow threads like How do I extract data from JSON with PHP?, but I can't see what I am doing wrong.
This is the code so far:
$api_results = '{"status":"0000","data":{"opening_price":"6998000","closing_price":"7270000","min_price":"6750000","max_price":"7997000","average_price":"7188302.5804","units_traded":"78484.9241002","volume_1day":"78484.9241002","volume_7day":"335611.84181738","buy_price":"7268000","sell_price":"7274000","date":"1510563513031"}}';
$results = json_decode($api_results, true);
// Some variations I tried:
var_dump($results->status[1]);
var_dump($results->data[1]->opening_price);
var_dump($results["data"][1]["opening_price"]);
End result: NULL NULL NULL
What am I doing wrong?
Thanks for the answers! I will upvote the working ones. Seems I got confused in the formating!
<?php
$api_results = '{"status":"0000","data":{"opening_price":"6998000","closing_price":"7270000","min_price":"6750000","max_price":"7997000","average_price":"7188302.5804","units_traded":"78484.9241002","volume_1day":"78484.9241002","volume_7day":"335611.84181738","buy_price":"7268000","sell_price":"7274000","date":"1510563513031"}}';
$results = json_decode($api_results, true);
print_r($results['status']);
echo "</br>";
print_r($results['data']['opening_price']);
Try access your array that way.
The output is :
0000
6998000
Keep an eye for the nested arrays. You need to access their parent array first in order to get their values.
Have you read the documentation of json_decode() (or, at least, the accepted answer of the question you linked)? If you pass TRUE as the second argument to json_decode() (and there is no decent reason to not pass it) then it decodes the JSON to associative arrays and not objects.
The elements in a PHP array can be accessed using the square bracket syntax.
A simple call to print_r($results) tells its structure:
Array
(
[status] => 0000
[data] => Array
(
[opening_price] => 6998000
[closing_price] => 7270000
[min_price] => 6750000
[max_price] => 7997000
[average_price] => 7188302.5804
[units_traded] => 78484.9241002
[volume_1day] => 78484.9241002
[volume_7day] => 335611.84181738
[buy_price] => 7268000
[sell_price] => 7274000
[date] => 1510563513031
)
)
Now, accessing its items is a piece of cake:
echo($results['status']);
# 0000
echo($results['data']['opening_price']);
# 6998000
Remove true from json_decode so you will have object result like Demo
$results = json_decode($api_results);
var_dump($results->status);
var_dump($results->data->opening_price);
When you use json_decode with true the returned objects will be converted into associative arrays.
Use this code like i think work it fine..
<?php
$api_results = '{"status":"0000","data":{"opening_price":"6998000","closing_price":"7270000","min_price":"6750000","max_price":"7997000","average_price":"7188302.5804","units_traded":"78484.9241002","volume_1day":"78484.9241002","volume_7day":"335611.84181738","buy_price":"7268000","sell_price":"7274000","date":"1510563513031"}}';
$results = json_decode($api_results);
print_r($results);
var_dump($results->status);
$var = $results->data;
var_dump($var->opening_price);
?>
stdClass Object
(
[status] => 0000
[data] => stdClass Object
(
[opening_price] => 6998000
[closing_price] => 7270000
[min_price] => 6750000
[max_price] => 7997000
[average_price] => 7188302.5804
[units_traded] => 78484.9241002
[volume_1day] => 78484.9241002
[volume_7day] => 335611.84181738
[buy_price] => 7268000
[sell_price] => 7274000
[date] => 1510563513031
)
)
string(4) "0000"
string(7) "6998000"
Remove true from json_decode and try something like this:
var_dump($results->status);
var_dump($results->data->opening_price);
If you see {} it is refering to objects and [] indicates that it is an array. You're trying to show everything as if they were arrays
You have set the second parameter of json_decode() to true. that means the json will be converted to an array so you are not able to access the data using pointer -> (because it is not an object).
You may access the data like this:
var_dump($results['status'][0]);
var_dump($results['data'][0]['opening_price']);
P.S: Try var_dump($results) to see the exact data, so you know how to access each attribute.

Could not convert json string to array using PHP

I need one help. I am unable to convert string to json array using PHP. I am explaining my code below.
$education=$_POST['education'];
the above line give this output [{'name':'aaa','id':'12'},{'name':'bbb','id':'20'}]. But its coming as a string .I tried to convert into array like below but it gived output as null
$edu=json_decode($education,true);
print_r($edu);
It gives the empty output. Here I need to convert it to array and populate all data. Please help me.
Hi You need to make your json string like below:
$arr = '[{"name":"aaa","id":"12"},{"name":"bbb","id":"20"}]';
$a = json_decode($arr);
echo "<pre>";
print_r($a);
die;
it will show your output like below:
Array
(
[0] => stdClass Object
(
[name] => aaa
[id] => 12
)
[1] => stdClass Object
(
[name] => bbb
[id] => 20
)
)
In php, you can use this function to check valid json:
function _isJsonString($string) {
json_decode($string);
return (json_last_error() == JSON_ERROR_NONE);
}
You can also check online for valid json: http://json.parser.online.fr/
Hope this will help.

How can I create a PHP stdClass Object from the output of a PHP stdClass Object

I have the following as a string:
stdClass Object
(
[createResult] => stdClass Object
(
[ReturnCode] => 1
)
)
How can I take the above string and create a new stdClass Object? I'd like to get the value like this:
$rc = $obj->createResults->ReturnCode;
If you can change the way it outputs into something like var_export, you can afterwards use that string with eval to get it back.
http://www.php.net/manual/en/function.var-export.php
If you can't change it (for whatever reason) and have to use the output of print_r, then you could try this recipe and see if it works for you. http://www.php.net/manual/en/function.print-r.php#93529
However, if at all possible, you should be storing data in a more portable format. You could use php's serialize => unserialize, or json_encode => json_decode, for starters.
You can also do it like this:
<?php
$s = "stdClass Object
(
[createResult] => stdClass Object
(
[ReturnCode] => 1
)
)";
$s = preg_match("/\s\[ReturnCode\] => \S+\s/", $s, $m);
echo preg_replace("/\s\[ReturnCode\] => (\S+)\s/", "$1", $m[0]);

Categories