JSON data revceiving PHP - php

The server receives from URL post string as below:
{
"head": {
"comm": 7,
"compress": false,
"ms": 1451029423348,
"encrypt": false,
"version": 2
},
"body": {
"data1": 0,
"data2": 59,
"data3": -40,
"data4": 0,
"data5": 0,
}
}
I have PHP file as below need to receive JSON format data from URL or java app sending post to server. Using server PHP ver 5.4.45, I can't change it.
$json = file_get_contents('php://input');
$string = get_magic_quotes_gpc() ? stripslashes($json) : $json;
$object = json_decode($string);
var_dump($object);
then i want to put to array each item in to array into $data variable each fields into $data array
I always receiving NULL , What can be the problem ?

If I paste your json here: http://jsonlint.com/ it gives a "Error: Parse error on line 14:"
Maybe it helps when you remove the comma after "data5": 0,

The JSON data is not correct. Try after removing the , after "data": 0.
Correct JSON :
{
"head": {
"comm": 7,
"compress": false,
"ms": 1451029423348,
"encrypt": false,
"version": 2
},
"body": {
"data1": 0,
"data2": 59,
"data3": -40,
"data4": 0,
"data5": 0
}
}

If, as you say, $json is NULL, the comma after "data5" is only because of text that was cut to make pasted code shorter, and you're using PHP <5.6 then according to http://php.net/manual/en/wrappers.php.php it could only be that either:
you're reading php://input multiple times (if not you then maybe a framework you're using or whatever);
the sender is passing data to you as multipart/form-data, which php://input cannot read.

try this:
$json = file_get_contents('php://input');
$string = get_magic_quotes_gpc() ? stripslashes($json) : $json;
$object = json_decode($string);
By using foreach function walk thru object elements and typecast them as an array
foreach($object as $k=>$v){
$data[$k] = (array)$v;
}
and the result will be as follows:
Array
(
[head] => Array
(
[comm] => 7
[compress] =>
[ms] => 1451029423348
[encrypt] =>
[version] => 2
)
[body] => Array
(
[data1] => 0
[data2] => 59
[data3] => -40
[data4] => 0
[data5] => 0
)
)

Related

Python to PHP | String to Multidimensional Json Object To Array

I have a python script which returns an object as string. I call this python script with php and then print out the result with var_dump(json_decode($result)) and get this (this it the right object I want so my python code works properly I guess):
string(467) "{"userData": {"geburtsdatum": "PMS_2018-01-01", "anrede": "PMS_Herr", "ID": "1", "nachname": "PMS_Nachname1", "Test": {"tel": "PMS_Tel1", "postalOptIn": 0, "postal": "S3_Postal1", "email": "PMS_EMail1"}, "vorname": "PMS_Vorname1" }} "
So as you can see its a string on php side.
But how can I convert it to an object now and the create a multidimensional array from it in php?
If you need more information pls ask Ill add it.
I tried:
json_decode($result, true);
json_decode($result);
$response = (array) $result;
all I get is an Array with 1 Index and the whole Object as Value in it.
The Object gets generated like this on python side:
for message in consumer:
if message.key == str.encode(sys.argv[1]):
returnValue = message.value #this here is an byte obj from external system
consumer.close()
print(returnValue.decode("latin-1"))
Edit 2 and Solution
After long search I found out that the service I'm using (3d Party) returns the result from the python script with json_encode(). I removed that and now this code works:
$array = json_decode($response, TRUE);
return var_dump($array);
Since it is a string you can decode it like this:
$string = '{"userData": {"geburtsdatum": "PMS_2018-01-01", "anrede": "PMS_Herr", "ID": "1", "nachname": "PMS_Nachname1", "Test": {"tel": "PMS_Tel1", "postalOptIn": 0, "postal": "S3_Postal1", "email": "PMS_EMail1"}, "vorname": "PMS_Vorname1" }}';
print_r(json_decode($string, true));
Which returns an array:
Array
(
[userData] => Array
(
[geburtsdatum] => PMS_2018-01-01
[anrede] => PMS_Herr
[ID] => 1
[nachname] => PMS_Nachname1
[Test] => Array
(
[tel] => PMS_Tel1
[postalOptIn] => 0
[postal] => S3_Postal1
[email] => PMS_EMail1
)
[vorname] => PMS_Vorname1
)
)

auto-incrementing ID on my JSON array

I've been trying to do this for a while now and I just can't seem to get it right. One post got me very close but not quite there because my of JSON's hierarchy. (it's an assignment and this hierarchy is mandatory.)
What I do right now is submit info from one page, POST it to my php on another page, save it in an array there, json_encode that array and write that to my JSON file.
Here is my watered-down code, hopefully getting rid of most unnecessary code:
<?php
$filename = "json/exercises.json";
$filesize = filesize($filename);
$fp = fopen($filename, "r+");
#Accept the submitted form
$exLanguage = $_POST['exLanguage'];
$exTitle = $_POST['exTitle'];
$exStuff = $_POST['exStuff'];
#write to JSON with an incrementing ID
if (file_get_contents($filename) == "") {
$exercise = array (
"id" => 1,
"lang" => $exLanguage,
"title" => $exTitle,
"main_object" =>
[
"exStuff" => $exStuff
]
);
$exercise_json = json_encode($exercise, JSON_PRETTY_PRINT);
file_put_contents($filename, $exercise_json, FILE_APPEND);
} else {
#Get the last set ID
$jsonid = json_decode(fread($fp, $filesize), true);
$last = end($jsonid);
$title = prev($jsonid);
$lang = prev($jsonid);
$id = prev($jsonid);
$exercise = array (
"id" => ++$id,
"lang" => $exLanguage,
"title" => $exTitle,
"main_object" =>
[
"exStuff" => $exStuff
]
);
$exercise_json = json_encode($exercise, JSON_PRETTY_PRINT);
file_put_contents($filename, $exercise_json, FILE_APPEND);
}
?>
now what this does is if my json is empty it adds the first array correctly with the ID at 1. Then if I try to add to my json again it adds it correctly with the ID at 2. But any more attempted writes to the JSON will give me these errors:
Warning: end() expects parameter 1 to be array, null given
Warning: prev() expects parameter 1 to be array, null given
Warning: prev() expects parameter 1 to be array, null given
Warning: prev() expects parameter 1 to be array, null given
I tried doing a
$reset = reset($jsonid);
after writing to file but that didn't work, just gave me another error on the 3rd write for the reset being given a null too.
Can anyone please tell me how to get this too work? Or if there is a much easier way of getting this done?
Understand JSON format first. Its a collection of Objects which means attribute: value pair wrapped in {} and separated by comma , and then again wrapped in {} OR [] at top level.
Your JSON structure is incomplete or corrupted. What you are doing currently will create JSON in following format in your JSON file:
{ "id": 1, "lang": "as", "title": "asdsad" }
{ "id": 2, "lang": "as", "title": "asdsad" }
{ "id": 3, "lang": "as", "title": "asdsad" }
{ "id": 4, "lang": "as", "title": "asdsad" }
So json_decode will return null in this case because of invalid JSON format.
You need to keep appending your new JSON in existing JSON such that above format will become like this:
[
{ "id": 1, "lang": "as", "title": "asdsad" },
{ "id": 2, "lang": "as", "title": "asdsad" },
{ "id": 3, "lang": "as", "title": "asdsad" },
{ "id": 4, "lang": "as", "title": "asdsad" }
]
Which means your else block is incorrect. Use following code in else block:
$jsonid = json_decode(file_get_contents($filename), true);
$last = end($jsonid);
$id = $last['id'];
$jsonid[] = array (
"id" => ++$id,
"lang" => $exLanguage,
"title" => $exTitle,
"main_object" => array("exStuff" => $exStuff)
);
$exercise_json = json_encode($jsonid, JSON_PRETTY_PRINT);
file_put_contents($filename, $exercise_json, FILE_APPEND);
I hope you are not bound to use that incorrect/corrupted JSON format. That will not work with json_decode() in any case.

PHP & JSON Decoding

I'm trying to decode some basic JSON data from Mintpal.com (https://www.mintpal.com/api)
The raw data looks like:
[
{
"market_id": "152",
"coin": "VeriCoin",
"code": "VRC",
"exchange": "BTC",
"last_price": "0.00008512",
"yesterday_price": "0.00009300",
"change": "-8.47",
"24hhigh": "0.00009450",
"24hlow": "0.00008050",
"24hvol": "13.153",
"top_bid": "0.00008063",
"top_ask": "0.00008591"
}
]
I just want to pull bits off this information out and assign them to variables. I use the below code with another near identical JSON output and it works fine.
//GET MINTPAL JSON DATA
$url = "https://api.mintpal.com/v1/market/stats/VRC/BTC";
$contents = file_get_contents($url);
$json = json_decode($contents);
//GET 'LAST BID' INFO
$lastBid = $json->code;
The previous raw JSON that works with the above code looks exactly the same, except for not being encased in '[...]' as the Mintpal one is.
{
"success": true,
"message": "",
"result": [
{
"MarketName": "BTC-LTC",
"High": 0.01126000,
"Low": 0.01060000,
"Volume": 442.30927821,
"Last": 0.01061100,
"BaseVolume": 4.86528601,
"TimeStamp": "2014-08-27T13:49:03.497",
"Bid": 0.01051801,
"Ask": 0.01061100,
"OpenBuyOrders": 50,
"OpenSellOrders": 116,
"PrevDay": 0.01079000,
"Created": "2014-02-13T00:00:00"
}
]
}
Any ideas on why I can't read the information this time round?
If you either did a var_dump() or a print_r() of your $json variable you should see that it is now an array starting at element 0 containing all the unique json elements.
//GET MINTPAL JSON DATA
$url = "https://api.mintpal.com/v1/market/stats/VRC/BTC";
$contents = file_get_contents($url);
$json = json_decode($contents);
pR($json);
//GET 'LAST BID' INFO
$lastBid = $json->code;
function pR($data){
echo "<pre>";
print_r($data);
echo "</pre>";
}
That yielded:
Array
(
[0] => stdClass Object
(
[market_id] => 152
[coin] => VeriCoin
[code] => VRC
[exchange] => BTC
[last_price] => 0.00008512
[yesterday_price] => 0.00009300
[change] => -8.47
[24hhigh] => 0.00009300
[24hlow] => 0.00008050
[24hvol] => 12.968
[top_bid] => 0.00008065
[top_ask] => 0.00008585
)
)

Searching JSON PHP

I have JSON that looks like this (shortened for readability):
{
"heroes": [
{
"name": "antimage",
"id": 1,
"localized_name": "Anti-Mage"
},
{
"name": "axe",
"id": 2,
"localized_name": "Axe"
},
{
"name": "bane",
"id": 3,
"localized_name": "Bane"
}
]
}
I have a PHP variable that is equal to one of the three ids. I need to search the JSON for the id and return the localized name. This is what I’m trying so far.
$heroid = $myplayer['hero_id'];
$heroes = file_get_contents("data/heroes.json");
$heroesarray = json_decode($heroes, true);
foreach ($heroesarray as $parsed_key => $parsed_value) {
if ($parsed_value['id'] == $heroid) {
$heroname = $parsed_value['localized_name'];
}
}
Easy. Just use json_decode(). Explanation follows the code at the bottom.
// First set the ID you want to look for.
$the_id_you_want = 2;
// Next set the $json.
$json = <<<EOT
{
"heroes": [
{
"name": "antimage",
"id": 1,
"localized_name": "Anti-Mage"
},
{
"name": "axe",
"id": 2,
"localized_name": "Axe"
},
{
"name": "bane",
"id": 3,
"localized_name": "Bane"
}
]
}
EOT;
// Now decode the json & return it as an array with the `true` parameter.
$decoded = json_decode($json, true);
// Set to 'TRUE' for testing & seeing what is actually being decoded.
if (FALSE) {
echo '<pre>';
print_r($decoded);
echo '</pre>';
}
// Now roll through the decoded json via a foreach loop.
foreach ($decoded as $decoded_array_key => $decoded_array_value) {
// Since this json is an array in another array, we need anothe foreach loop.
foreach ($decoded_array_value as $decoded_key => $decoded_value) {
// Do a comparison between the `$decoded_value['id']` and $the_id_you_want
if ($decoded_value['id'] == $the_id_you_want) {
echo $decoded_value['localized_name'];
}
}
}
Okay, the reason my first try at this did not work—and neither did yours—is your JSON structure was nested one more level deep that what is expected. See the debugging code I have in place with print_r($decoded);? This is the output when decoded as an array:
Array
(
[heroes] => Array
(
[0] => Array
(
[name] => antimage
[id] => 1
[localized_name] => Anti-Mage
)
[1] => Array
(
[name] => axe
[id] => 2
[localized_name] => Axe
)
[2] => Array
(
[name] => bane
[id] => 3
[localized_name] => Bane
)
)
)
First you have an array to begin with which could equate to $decoded[0] and then below that you have another array that equates to $decoded[0]['heroes'] and then in there is the array that contains the values which is structured as $decoded[0]['heroes'][0], $decoded[0]['heroes'][1], $decoded[0]['heroes'][2].
But the key to solving this was the print_r($decoded); which helped me see the larger structure of your JSON.
json_decode() takes a JSON string and (if the second parameter is true) turns it into an associate array. We then loop through this data with a foreach until we find the hero you want.
$json = ''; // JSON string
$data = json_decode($json, true);
foreach($data['heroes'] as $hero) {
if($hero['id'] === 2) {
var_dump($hero['localized_name']);
// Axe
// This will stop the loop, if you want to keep going remove this line
break;
}
}

PHP: setting a number as key in associative array

I'm trying to recreate json from a DB, for the client side. Unfortunately some of the keys in the json are numbers, which work fine in javascript, however as a result PHP keeps treating them as numeric instead of associative arrays. each key is for a document. let me show you:
PHP:
$jsonobj;
while ($row = mysql_fetch_assoc($ms)) {
$key = strval($row["localcardid"]);
$jsonobj[$key] = json_decode($row["json"]);
}
// $jsonobj ist still a numeric array
echo json_encode($jsonobj);
the resulting json should look like this:
{
"0": {
"terd": "10",
"id": 0,
"text": "",
"pos": 1,
"type": 0,
"divs": [
{},
{}
],
"front": 1
}
"1": {
"terd": "10",
"id": 0,
"text": "",
"pos": 1,
"type": 0,
"divs": [
{},
{}
],
"front": 1
}
}
One obvious solution would be to save the whole json without splitting in up. however that doesnt seem wise in regards to the db. i wanna be able to access each document seperately. using
$jsonobj = array ($key => json_decode($row["json"]));
obviously works, but unfortunately just for one key...
EDIT: for clarification*
in php: there's a difference between
array("a", "b", "c")
and
array ("1" => "a", "2" => "b", "3" => "c").
the latter, when done like this $array["1"] = "a" results in array("a") instead of array("1" => "a")
ANSWERED HERE
Try
echo json_encode((object)$jsonobj);
I believe if you pass the JSON_FORCE_OBJECT option, it should output the object with numeric indexes like you want:
$obj = json_encode($jsonObj, JSON_FORCE_OBJECT);
Example:
$array = array();
$array[0] = array('test' => 'yes', 'div' => 'first', 'span' => 'no');
$array[1] = array('test' => 'no', 'div' => 'second', 'span' => 'no');
$array[2] = array('test' => 'maybe', 'div' => 'third', 'span' => 'yes');
$obj = json_encode($array, JSON_FORCE_OBJECT);
echo $obj;
Output:
{
"0": {
"test": "yes",
"div": "first",
"span": "no"
},
"1": {
"test": "no",
"div": "second",
"span": "no"
},
"2": {
"test": "maybe",
"div": "third",
"span": "yes"
}
}
Simply save both inside a single entry in the database: the separate field values AND the whole json structure inside a separate column. This way you can search by single fields and still get the valid json structure for easy handling.
For setting a number as key in associative array we can use following code
$arr=array(); //declare array variable
$arr[121]='Item1';//assign Value
$arr[457]='Item2';
.
.
.
print_r($arr);//print value

Categories