[英]how to decode json data in php file
我想解碼來自android的json數據
["{\"User_Registartion_Details\":{\"fullname\":\"ssss\",\"emailid\":\"sumitbwm@gmail.com\",\"mobile\":\"8796485577\",\"location\":\"pune\"}}"]
怎么做....從json獲取數據並使用php腳本嘗試將其保存在我的sql數據庫中,但在我的sql中顯示空值。 這是我的php代碼,它獲取json數據並進行解碼,然后保存在database.I嘗試,但存儲了空值(空白)。 數據以json格式從android頁面獲取並在php腳本中解碼,保存在db..anyboday中對此有所了解,請help..i在android / php中是新的。
這是我的php代碼,它獲取json數據並進行解碼,然后保存在數據庫中
<?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);
PHP中的JSON編碼和解碼是使用json_encode
和`json_decode``函數完成的。
// 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;
您的問題是您的json字符串不正確。 我不得不對其解碼兩次,以使其正常工作。
// 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"
}
}
您可以通過查看$_POST
變量來訪問您的請求
當在請求中使用application / x-www-form-urlencoded或multipart / form-data作為HTTP Content-Type時,通過HTTP POST方法傳遞給當前腳本的變量的關聯數組。
使用var_dump($_POST);
// 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));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.