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);
?>
Related
I need to decode the below json from a mobile app
Array
(
[{"unm":"admin","pw”:”password”}] =>
)
and my php code is
$obj1 = print_r($_REQUEST, true); //get $_request variable data(responce of login) data as it is
foreach($obj1 as $key => $value)
{
$obj2 = $key; //get first key
}
$obj3 = json_decode($obj2); //decode json data to obj3
$mob_user_name = $obj2['unm']; //getting json username field value
$mob_user_password = $obj2['pw']; //getting json password field value
Hope this will fix your issue,
Note: content is nothing but which you have received from iOS app
content = Array (
[{"unm":"admin","pw”:”password”}] => )
parse that in php
$json = json_decode($content, true);
print json[0]['unm']; /* prints the username */
print json[0]['pw']; /* prints the password */
{"unm":"admin","pw”:”password”} is an object, and json_decode() will by default build it as so.
$obj = json_decode('{"unm":"admin","pw”:”password”}');
echo $obj->unm;
echo $obj->pw;
If for some reason you want it to be converted to an associative array, set the second parameter of json_decode() to true as specified in the manual.
$arr = json_decode('{"unm":"admin","pw”:”password”}', true);
echo $arr['unm'];
echo $arr['pw'];
My wsdl file :-
<?php
/**
#Description: Book Information Server Side Web Service:
This Sctript creates a web service using NuSOAP php library.
fetchBookData function accepts ISBN and sends back book information.
#Author: http://programmerblog.net/
#Website: http://programmerblog.net/
*/
require_once('dbconn.php');
require_once('lib/nusoap.php');
$server = new nusoap_server();
/* Fetch 1 book data */
function presentStatusPull($rnbcode){
global $dbconn;
$sql = "SELECT * FROM rnb_gpl_data where did = :rnbcode";
// prepare sql and bind parameters
$stmt = $dbconn->prepare($sql);
$stmt->bindParam(":rnbcode", $rnbcode);
// insert a row
$stmt->execute();
$data = $stmt->fetch(PDO::FETCH_ASSOC);
return json_encode($data);
$dbconn = null;
}
$server->configureWSDL('index', 'urn:index');
$server->register('presentStatusPull',
array('rnbcode' => 'xsd:string'),
array('data' => 'xsd:string'),
'urn:index',
'urn:index#presentStatusPull'
);
$server->service(file_get_contents("php://input"));
?>
Then my php file for call the wsdl server:-
<?php
require_once('lib/nusoap.php');
$result = array();
$wsdl = "http://meter.digireach.com/RnBCode/index.php?wsdl";
$rnbcode = $_GET['rnbcode'];
//create client object
$client = new nusoap_client($wsdl, true);
$result = $client->call('presentStatusPull', array($rnbcode));
// $result = json_decode($result);
// echo json_encode($result);
echo json_encode($result, JSON_NUMERIC_CHECK);
?>
and response of url :- http://meter.digireach.com/RnBCode/presentstatus.php?rnbcode=DR00098EM
and output is like this:-
"{\"srno\":\"1\",\"tr_date\":\"2017-08-22 11:53:33\",\"did\":\"DR00098EM\",\"p1\":\"455\",\"p2\":\"0\",\"p3\":\"0\",\"p4\":\"48\",\"p5\":\"0\",\"p6\":\"0\",\"p7\":\"60\",\"p8\":\"40\",\"p9\":\"0\",\"p10\":\"0\",\"p11\":\"5\",\"p12\":\"0\",\"p13\":\"0\",\"p14\":\"1103\",\"p15\":\"36170\",\"p16\":\"511046\",\"p17\":\"0\",\"p18\":\"1\",\"p19\":\"1\",\"p20\":\"1\",\"tno\":\"Ideal\",\"ser_date\":\"2017-08-22 11:54:12\"}"
so,I want to remove backslash() from this json response.
You didn't set valid JSON header this is why your API response is string not JSON.
Solution 1:
You should set valid Content-Type header before JSON output. Like following:
header('Content-Type: application/json');
echo json_encode($result, JSON_NUMERIC_CHECK);
or, Solution 2:
Decode your output twice json_decode(json_decode($json))
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
I want to know how can I do to convert neo4j database to json file using PHP.
I used the code below but i want to know the similar of mysqli_fetch_assoc in Neo4j:
$req= "match n return n";
$result = $client->sendCypherQuery($req)->getResult(); //create an array
$emparray[] = array();
while($row =mysqli_fetch_assoc($result)) { $emparray[] = $row; }
echo json_encode($emparray); //write to json file
$fp = fopen('data/charlize.json', 'w');
fwrite($fp, json_encode($emparray));
fclose($fp);
to get all of your database as a JSON you can simply send a post request to http://<your database ip>/db/data/cypher with param "query" : "Match a return a" this will return a JSON string as response, then you can do whatever you want (print it in a file for example).
I've got a really weird problem and I can't figure out why.
The situation is quite simple. My Android app uploads JSON data to a php script on my server. Right now I am trying to parse the data.
This is the JSON-Array passed to the script (via httpPost.setEntity ()):
[{"friends_with_accepted":"false","friends_with_synced":"false","friends_with_second_id":"5","friends_with_first_id":"6"}]
This is the php script:
<?php
// array for JSON response
$response = array();
$json = file_get_contents ('php://input');
$jsonArray = json_decode ($json, true);
foreach ($jsonArray as $jsonObject) {
$firstId = $jsonObject['friends_with_first_id'];
$accepted = $jsonObject ['friends_with_accepted'];
$secondId = $jsonObject ['friends_with_second_id'];
$synced = $jsonObject ['friends_with_synced'];
echo "accepted: ".$accepted."synced: ".$synced;
} ?>
And this is the response I get from the script:
accepted: synced: false
Why is the "synced" property correctly passed, but not the "accepted" property??
I can't see the difference. Btw, firstId and secondId are parsed correctly as well.
Okay, i just found the problem:
Instead of
$accepted = $jsonObject ['friends_with_accepted'];
I deleted the space between jsonObject and the bracket
$accepted = $jsonObject['friends_with_accepted'];