I want to decode json data which come from android like
["{\"User_Registartion_Details\":{\"fullname\":\"ssss\",\"emailid\":\"sumitbwm#gmail.com\",\"mobile\":\"8796485577\",\"location\":\"pune\"}}"]
how to do it....get data from json and save in my sql db suing php script trying but in my sql show null values. This my php code which get json data and decode then save in database.I tried but but store null values(blank).
Data get from android page in json format and decode in php script the save in db..anyboday have idea about this please help..i new in android/php.
This my php code which get json data and decode then save in database
<?php
// Include confi.php
include_once('conection.php');
if($_SERVER['REQUEST_METHOD'] == "POST" && $_SERVER["CONTENT_TYPE"] == "application/json")
{
$request = file_get_contents('php://input');
$array = json_decode($request,true);
$name = $array['fullname'];
$email = $array['emailid'] ;
$mobileno = $array['mobile'] ;
$location = $array['location'];
$sql = "INSERT INTO usertable (`fullname`, `emailid`, `mobile`, `location`) VALUES ('$array[name]', '$array[email]', '$array[mobileno]', '$array[location]')";
$qur = mysql_query($sql);
if($qur)
{
$json = array("status" => 1, "msg" => "Done User added!");
}
else
{
$json = array("status" => 0, "msg" => "Error adding user!");
}
}else
{
$json = array("status" => 0, "msg" => "Request method not accepted");
}
#mysql_close($conn);
/* Output header */
header('Content-type: application/json');
echo json_encode($json);
JSON Encoding and Decoding in PHP is done using the json_encode and `json_decode``functions.
// To encode
$encodes = json_encode($json);
// To decode
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
$decoded = json_decode($json);
// To see which variables are inside your decoded json
echo "<pre>";
var_dump($decoded);
echo "</pre>";
exit;
Edit
Your problem is that your json string is incorrect. I had to decode it twice to make it work.
// Incorrect json string
$json = '["{\"User_Registartion_Details\":{\"fullname\":\"ssss\",\"emailid\":\"sumitbwm#gmail.com\",\"mobile\":\"8796485577\",\"location\":\"pune\"}}"]';
// Correct Json string
$json = '{"User_Registartion_Details":{"fullname":"ssss","emailid":"sumitbwm#g‌​mail.com","mobile":"8796485577","location":"pune"}}';
echo "<pre>";
var_dump(json_decode($json));
object(stdClass)#25 (1) {
["User_Registartion_Details"]=>
object(stdClass)#19 (4) {
["fullname"]=>
string(4) "ssss"
["emailid"]=>
string(24) "sumitbwm#g‌​mail.com"
["mobile"]=>
string(10) "8796485577"
["location"]=>
string(4) "pune"
}
}
You can access your request by looking at the $_POST variable
An associative array of variables passed to the current script via the HTTP POST method when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request.
Display it using var_dump($_POST);
Example
// Your android application sends a request
// This request is part of the HTTP protocol
// It is either a POST, GET, PUT or DELETE request
// PHP handles PUT and DELETE as a POST request
// The request data will be stored in the $_POST varaible and the $_REQUEST variable
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Use a var_dump to learn what key holds the json data
var_dump($_POST);
// let's say its in $_POST['json']
$json = $_POST['json'];
var_dump(json_decode($json));
}
Resources
json_encode() - Manual
json_decode() - Manual
Related
I have a PHP file which is displaying some posted data:
$data = file_get_contents('php://input');
echo json_encode($data);
The above returns:
{"name":"mark","item":"car"}
Now I want to echo just the name so I tried:
echo $data[0].name;
But that's giving me Error: [Object].[Object]
How can I fix this?
You need to decode your JSON input first:
// $data is an input string
$data = file_get_contents('php://input');
// convert input string to PHP array
$data = json_decode(data, true);
// echo just the name
echo $data['name'];
// dump the whole parsed input
var_dump($data);
I have a large python dictionary, which is sent out as a JSON in a POST request using the py requests library to a web service which accepts incoming JSONs (XAMPP/PHP set up in localhost).
When I receive the transmitted JSON data through the POST request, PHP always gives the output as array, and not as a serialized JSON string.
Secondly, nested elements are missing from the data captured on PHP end.
I am using the following snip to do the job.
Python code :
import json
import requests
dummy_data = {
"param1": "ABCDEF",
"param2": {
"0": "inner_data_0",
"1": "inner_data_1"
},
"param3": {
"very_big_text_key_1": {
"inner_key_1": "inner_value_1",
"inner_key_2": ["very_large_string_item_as_inner_value_2"],
"inner_key_3": "inner_value_3"
},
"very_big_text_key_2": {
"inner_key_1": "inner_value_1",
"inner_key_2": ["very_large_string_item_as_inner_value_2"],
"inner_key_3": "inner_value_3"
}
}
}
headers = {'Content-Type': 'application/json', 'accept' : 'application/json'}
r = requests.post("http://localhost/test/data.php", params = (dummy_data), headers = headers)
print (r.text)
Also tried with :
headers = {'Content-Type': 'application/json'}
Both give the same output as below:
*Hello World!<br/>Printing GET array ...<br/>array(4) {
["param1"]=>
string(6) "ABCDEF"
["param2"]=>
string(1) "1"
["param3"]=>
string(19) "very_big_text_key_2"
["param4"]=>
string(6) "GHIJKL"
}
<br/>Printing POST array ...<br/>array(0) {
}*
I used json and data as parameters to "requests".
r = requests.post("http://localhost/test/data.php", json = (dummy_data), headers = headers)
and
r = requests.post("http://localhost/test/data.php", data = (dummy_data), headers = headers)
Output is as below :
*Hello World!<br/>Printing GET array ...<br/>array(0) {
}
<br/>Printing POST array ...<br/>array(0) {
}*
I am accepting data as follows in PHP code:
<?php
print "Hello World!";
echo "<br/>";
print "Printing GET array ...";
echo "<br/>";
var_dump($_GET);
echo "<br/>";
print "Printing POST array ...";
echo "<br/>";
var_dump($_POST);
?>
The inner text doesn't seem to be appearing in any of the scenarios. I have tried to implement some solutions as suggested by members of stackoverflow. But still i am facing the above mentioned issue.
The problem is now resolved. The resolution happend after consideration of the following points:
JSON passed by Python is not de-serialized by default, by PHP and has to be serialized, after inspection of "Content-type" header.
Once de-serialized, the passed JSON content was then used for further processing.
Hence the key to solve the problem was, to check the content-length, and content-type headers. If content-length was found greater than 0 and content type was application/json, the incoming JSON can be de-serialized using json_decode().
The code snips for PHP and Python, using which the following was accomplished is as below:
On the Python side:
import json
import requests
dummy_data = {
"param1": "ABCDEF",
"param2": {
"0": "inner_data_0",
"1": "inner_data_1"
},
"param3": {
"very_big_text_key_1": {
"inner_key_1": "inner_value_1",
"inner_key_2": ["very_large_string_item_as_inner_value_2"],
"inner_key_3": "inner_value_3"
},
"very_big_text_key_2": {
"inner_key_1": "inner_value_1",
"inner_key_2": ["very_large_string_item_as_inner_value_2"],
"inner_key_3": "inner_value_3"
}
}
}
headers = {'Content-Type': 'application/json'}
r = requests.post("http://localhost/test/data.php", data = json.dumps(dummy_data), headers=headers)
print (r.text)
On the PHP side:
...
if(#$_SERVER["CONTENT_LENGTH"] > 0){
$contentType = $_SERVER["CONTENT_TYPE"];
if($contentType == "application/json"){
$decoded_data = json_decode(file_get_contents("php://input"), true);
}
else{
echo "Incoming data is not a JSON!";
}
return $decoded_data;
}
I am trying to get JSON posted by an android application and decode it into an array to store it in my sqldb.
I have written the following php code. When I execute it, it displays [] (line 6).
<?php
include_once './db_functions.php';
//Create Object for DB_Functions class
$db = new DB_Functions();
//Get JSON posted by Android Application
$json = (isset($_POST["usersJSON"])? $_POST["usersJSON"] : '');
//Remove Slashes
if (get_magic_quotes_gpc()){
$json = stripslashes($json);
}
//Decode JSON into an Array
$data = json_decode($json);
//Util arrays to create response JSON
$a=array();
$b=array();
//Loop through an Array and insert data read from JSON into MySQL DB
for($i=0; $i<count($data) ; $i++)
{
//Store User into MySQL DB
$res = $db->storeUser($data[$i]->userId,$data[$i]->userName);
//Based on insertion, create JSON response
if($res){
$b["id"] = $data[$i]->userId;
$b["status"] = 'yes';
array_push($a,$b);
}else{
$b["id"] = $data[$i]->userId;
$b["status"] = 'no';
array_push($a,$b);
}
}
//Post JSON response back to Android Application
echo json_encode($a);
?>
I'm having difficulties grabbing any of the JSON information from this URL.
I've tried other JSON snippets and they seem to work so I'm not sure if it's the way that the URL is structured or something.
Basic example below.
<?php
$json = file_get_contents('http://nhs-sh.cfpreview.co.uk/api/version/fetchLatestData?dataType=Clinics&versionNumber=-1&uuID=website&dt=');
$obj = json_decode($json);
echo "Body: " . $obj->Body;
?>
The link provided starts with
{ data :
which is valid javascript but invalid json. You can test it on http://jsonlint.com. To fix this we can replace the data with "data" :
$json = file_get_contents('http://nhs-sh.cfpreview.co.uk/api/version/fetchLatestData?dataType=Clinics&versionNumber=-1&uuID=website&dt=');
$obj = json_decode($json);
if (json_last_error() !== JSON_ERROR_NONE) { //check if there was an error decoding json
$json = '{ "data" :'. substr(trim($json), 8); // replace the first 8-1 characters with { "data" :
$obj = json_decode($json);
}
print_r($obj->data); //show contents of data
Please note that this fix is dependent on the data source e.g. if they change data to dataset. The correct measure would be to ask the developers to fix their json implementation.
I am in the process of trying to call a php script over http and receive a json object back from where I plan to process further.
Basically, the code is as follows:
<?php
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
$version=$_GET["v"];
$product=$_GET["p"];
$stream=$_GET["s"];
$cmd=$_GET["c"];
$string = file_get_contents("http://localhost:82/releasenote/src/getTSBDetails.php?p=$product&v=$version&s=$stream&c=$cmd");
print_r($string);
exit();
} else {
print("2");
$string = file_get_contents('tsbDetails.json');
}
When the get_file_contents http request is called directly in the browser, the output is a json, but when trying using the above there is no response.
<?php
// JSon request format is :
// {"userName":"654321#zzzz.com","password":"12345","emailProvider":"zzzz"}
// read JSon input
$data_back = json_decode(file_get_contents('php://input'));
// set json string to php variables
$userName = $data_back->{"userName"};
$password = $data_back->{"password"};
$emailProvider = $data_back->{"emailProvider"};
// create json response
$responses = array();
for ($i = 0; $i < 10; $i++) {
$responses[] = array("name" => $i, "email" => $userName . " " . $password . " " . $emailProvider);
}
// JSon response format is :
// [{"name":"eeee","email":"eee#zzzzz.com"},
// {"name":"aaaa","email":"aaaaa#zzzzz.com"},{"name":"cccc","email":"bbb#zzzzz.com"}]
// set header as json![enter image description here][2]
header("Content-type: application/json");
// send response
echo json_encode($responses);
?>
[1]: http://i.stack.imgur.com/I7imt.jpg
[2]: http://i.stack.imgur.com/XgvOT.jpg
First of all you should make sure your variables can be used in the url:
$version=urlencode($_GET["v"]);
$product=urlencode($_GET["p"]);
$stream=urlencode($_GET["s"]);
$cmd=urlencode($_GET["c"]);
Then you should check if the value you read in $string is valid json. You can use this answer for that.
Then, if your string contains valid json, you should just echo it.
Finally, if you always expect json from your script, you should also json_encode your error handling:
} else {
echo json_encode("2");
// $string = file_get_contents('tsbDetails.json'); /* commented out as you don't seem to use it */
}