Reputation: 91
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 ?
Upvotes: 1
Views: 135
Reputation: 783
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
)
)
Upvotes: 0
Reputation: 10420
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:
php://input
multiple times (if not you then maybe a framework you're using or whatever);multipart/form-data
, which php://input
cannot read.Upvotes: 0
Reputation: 1296
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
}
}
Upvotes: 0
Reputation: 163477
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,
Upvotes: 4