Decode json in php and create variables - php

I a trying to decode a json callback.
The json code is posted to callback.php - Here is an example of the json:
{
"order": {
"id": "5RTQNACF",
"created_at": "2012-12-09T21:23:41-08:00",
"status": "completed",
"total_btc": {
"cents": 100000000,
"currency_iso": "BTC"
},
"total_native": {
"cents": 1253,
"currency_iso": "USD"
},
"custom": "order1234",
"receive_address": "1NhwPYPgoPwr5hynRAsto5ZgEcw1LzM3My",
"button": {
"type": "buy_now",
"name": "Alpaca Socks",
"description": "The ultimate in lightweight footwear",
"id": "5d37a3b61914d6d0ad15b5135d80c19f"
},
"transaction": {
"id": "514f18b7a5ea3d630a00000f",
"hash": "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b",
"confirmations": 0
},
"customer": {
"email": "coinbase#example.com",
"shipping_address": [
"John Smith",
"123 Main St.",
"Springfield, OR 97477",
"United States"
]
}
}
}
I can echo the json and get the following response:
{"order""id":null,"created_at":null,"status":"completed","total_btc":{"cents":100000000,"currency_iso":"BTC"},"total_native":{"cents":83433,"currency_iso":"USD"},"custom":"123456789","receive_address":"1A2qsxGHo9KjtWBTnAopTwUiBQf2w6yRNr","button":{"type":"buy_now","name":"Test Item","description":null,"id":null},"transaction":{"id":"52d064b59eeb59985e00002c","hash":"4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b","confirmations":0}}}
However if I try to decode the json using the following:
$array = json_decode($jsonString, true);
echo $array;
I get the following response: "200 Array"
I want to be able turn each json parameter in to a php variable.

You can access the variables within $array, for example by doing:
echo $array['custom']; // prints out "order1234"
You don't want to extract the variables directly into the local lexical scope of your program as that would create security concerns. Just use the data as indicated in the snippet above.

Related

Show JSON data from Request Body POST [duplicate]

As a test, this JSON data is being POSTed to my website:
{
"order": {
"id": null,
"created_at": null,
"status": "new",
"total_btc": {
"cents": 100000000,
"currency_iso": "BTC"
},
"total_native": {
"cents": 2263,
"currency_iso": "USD"
},
"custom": "123456789",
"button": {
"type": "buy_now",
"name": "Test Item",
"description": null,
"id": null
},
"transaction": {
"hash": "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b",
"confirmations": 0
}
}
}
Since it is being sent server-to-server I cannot visibly see the data. I have tried sending the $_POST array to a text file, but it comes up blank. What I think I need to do is:
$data = json_decode($jsonData);
But how do I set the variable $jsonData?
You can try to use wrappers for reading raw POST query.
$data = file_get_contents("php://input");
Have you tried this, store the sting obtained to a variable and then decoding it?
$postedJsonData= '{"order":{"id":null,"created_at":null,"status":"new","total_btc":
{"cents":100000000,"currency_iso":"BTC"},"total_native":
{"cents":2263,"currency_iso":"USD"},"custom":"123456789","button":
{"type":"buy_now","name":"Test Item","description":null,"id":null},"transaction":
{"hash":"4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b","confirmations":0}}}';
var_dump(json_decode($postedJsonData, true));
The true parameter would return an associative array
$data = json_decode($jsonData, True);

How to read JSON results from PHP

How to access element of below json output using php ..
{
"ISBN:9781430215752": {
"bib_key": "ISBN:9781430215752",
"preview":
"restricted",
"preview_url":
"https://archive.org/details/linuxrecipesforo00kuhn",
"info_url": "https://openlibrary.org/books/OL23936576M/Linux_recipes_for_Oracle_DBAs",
"details": {
"lc_classifications": ["QA76.9.D3 K84 2009"],
"latest_revision": 2,
"ocaid": "linuxrecipesforo00kuhn",
"contributions": ["Kim, Charles.", "Lopuz, Bernard."],
"source_records": ["marc:marc_loc_updates/v37.i44.records.utf8:10470755:1047"],
"title":
"Linux recipes for Oracle DBAs",
"languages": [{
"key": "/languages/eng"
}],
"subjects": ["Linux", "Oracle (Computer file)", "Relational databases", "Database management"],
"publish_country": "cau",
"by_statement": "Darl Kuhn, Charles Kim, Bernard Lopuz.",
"type": {
"key": "/type/edition"
},
"revision": 2,
"other_titles": ["Linux recipes for Oracle DataBase Administrators"],
"publishers": ["Apress", "Distributed to the book trade by Springer-Verlag"],
"last_modified": {
"type": "/type/datetime",
"value": "2014-04-06T06:55:36.956977"
},
"key": "/books/OL23936576M",
"authors": [{
"name": "Darl Kuhn",
"key": "/authors/OL1484587A"
}],
"publish_places": ["Berkeley, CA", "New York"],
"oclc_number": ["243543902"],
"pagination": "xxv, 501 p. :",
"created": {
"type": "/type/datetime",
"value": "2009-11-24T23:42:39.524606"
},
"dewey_decimal_class": ["005.75/65 22", "005.26/8"],
"notes": {
"type": "/type/text",
"value": "Includes index."
},
"number_of_pages": 501,
"isbn_13": ["9781430215752"],
"lccn": ["2009277832"],
"isbn_10": ["1430215755"],
"publish_date": "2008"
}
}
}
I tried using below code,
it doesn't work.
$json = json_decode($body);
echo $json->ISBN:9780980200447->info_url;
It's giving an error..
Is there any other easy way to read all elements?
You are on the right track. : is just an invalid character for a property and must be handled special.
echo $json->{'ISBN:9781430215752'}->info_url;
will get you the expected result.
You may also decode as an associative array
$json = json_decode($body, true);
echo $json['ISBN:9781430215752']['info_url'];
I would probably stick to this approach rather than the object oriented, since encapsulating keys makes code less readable
You must use
echo $json->{'ISBN:9780980200447'}->info_url;
since 'ISBN:9780980200447' is your class name.
Reference: php.net
<?php
$json = '{"foo-bar": 12345}';
$obj = json_decode($json);
print $obj->{'foo-bar'}; // 12345
?>
Use braces like this:
echo $json->{'ISBN:9781430215752'}->info_url;

How do I turn a POSTed JSON value into PHP?

As a test, this JSON data is being POSTed to my website:
{
"order": {
"id": null,
"created_at": null,
"status": "new",
"total_btc": {
"cents": 100000000,
"currency_iso": "BTC"
},
"total_native": {
"cents": 2263,
"currency_iso": "USD"
},
"custom": "123456789",
"button": {
"type": "buy_now",
"name": "Test Item",
"description": null,
"id": null
},
"transaction": {
"hash": "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b",
"confirmations": 0
}
}
}
Since it is being sent server-to-server I cannot visibly see the data. I have tried sending the $_POST array to a text file, but it comes up blank. What I think I need to do is:
$data = json_decode($jsonData);
But how do I set the variable $jsonData?
You can try to use wrappers for reading raw POST query.
$data = file_get_contents("php://input");
Have you tried this, store the sting obtained to a variable and then decoding it?
$postedJsonData= '{"order":{"id":null,"created_at":null,"status":"new","total_btc":
{"cents":100000000,"currency_iso":"BTC"},"total_native":
{"cents":2263,"currency_iso":"USD"},"custom":"123456789","button":
{"type":"buy_now","name":"Test Item","description":null,"id":null},"transaction":
{"hash":"4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b","confirmations":0}}}';
var_dump(json_decode($postedJsonData, true));
The true parameter would return an associative array
$data = json_decode($jsonData, True);

Error in json_decode

I have the following json, I'm sending through AJAX, but in the server side the json_decode returning an empty array. I'm sending different values as well, and in that case it's working fine. I check int this link, and this is a valid JSON.
[
{
"name": "bettype",
"value": "All"
},
{
"name": "bookies",
"value": "Interwetten"
},
{
"name": "sporttype",
"value": "Soccer"
},
{
"name": "team1",
"value": "Braunschweig"
},
{
"name": "team2",
"value": "Bayern Munich"
},
{
"name": "league",
"value": "Germany DFB Cup (90`)"
}
]
UPDATED:
this is the server side code:
var_dump((stripslashes($_GET['data']));
var_dump(json_decode(stripslashes($_GET['data'])));
and this is the output:
string(244) "[{"name":"bettype","value":"All"},{"name":"bookies","value":"Interwetten"},{"name":"sporttype","value":"Soccer"},{"name":"team1","value":"Braunschweig"},{"name":"team2","value":"Bayern Munich"},{"name":"league","value":"Germany DFB Cup (90�)"}]" NULL
It works fine for me.
http://sandbox.phpcode.eu/g/80941.php
Check your browser configuration/charset and try again

imploding array_keys from Facebook JSON data

Need some help with the sample code provided the facebook. I can't get it to return a series of IDs that I need to run a sql query against.
$friends = '{
"data": [
{
"name": "Paul",
"id": "12000"
},
{
"name": "Bonnie",
"id": "120310"
},
{
"name": "Melissa",
"id": "120944"
},
{
"name": "Simon",
"id": "125930"
},
{
"name": "Anthony",
"id": "120605"
},
{
"name": "David",
"id": "120733"
}
]
}';
$obj = json_decode($friends);
print $obj->{'data'}[0]->{'name'};
I can return the "Paul"
what I want is to return all the id's using implode(array_keys($obj),",")
I am only getting data to return.
What I'd like to do is retrieve all the IDs separated by a comma.
Thanks!
Try implode-ing on the data key with array_map:
function get_id($o) {
return $o->id;
}
implode(array_map('get_id', $obj->data),",")

Categories