开发者

how to get json data from iphone post request

I am developing an iPhone App using JSON framework, I am calling a PHP script to update MySQL database on local server. Using these code:

NSString *jsonString = [sendData JSONRepresentation];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSString*post = [NSString stringWithFormat:@"&json=%@", jsonString];
NSData*postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:NO];

[request setURL:[NSURL URLWithString:@"http://localhost:8888/update.php"]];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
[r开发者_如何学JAVAequest setHTTPBody:postData];

I would like to ask:

What is the PHP script to get data from that request, and how I can decode JSON data to PHP object to update to database?

Any help would be appreciated.


I haven't done this with the iPhone but looks like it will just be:

if(isset($_REQUEST['json']) && $_REQUEST['json']) {
    $jsonObj = json_decode($_REQUEST['json']);
    //mandatory sanitizing and verification here
    //PDO examples
    //$stmt = $db->prepare('INSERT ...');
    //$stmt->execute(array($jsonObj->userId, $jsonObj->specialData));
    //check statement execution
}

More info:

http://php.net/json_decode

http://php.net/pdo


Here are some lines of code with the limited info you provided

<?php
// get data
$rawJsonData = $_POST;
$decodedData = json_decode($rawJsonData);

// .. do some parsing on $decodedData ..

// save data
$db = new Db();
$db->insert('table', $decodedData);

The $decodedData will be a PHP array which you can process in any way you need and then save into db.


You will find your data in the variable $_POST['json'], you can take a look at what you have received via POST by using:

<?php print_r($_POST); ?>

Once you have identified where is your data, you can pass from JSON to PHP data using:

<?php $phpObj = json_decode($_POST['json']); ?>

Again, you can use print_r to look at the structure of your data:

<?php print_r($phpObj); ?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜