How to retrieve array in php sent from iOS

2019-05-29 17:53发布

问题:

Following is my iOS code that sends NSmutable Array to PHP webservice:

 // Getting Server Address
            AppDelegate *appDelegate =
            [[UIApplication sharedApplication] delegate];

            NSString *serverAddress = [appDelegate getServerAddress];

            serverAddress = [serverAddress stringByAppendingString:@"ABC.php"];


            NSLog(@"Server Address: %@",serverAddress);

            NSData *post = [NSJSONSerialization dataWithJSONObject:UsersArray options:NSJSONWritingPrettyPrinted error:nil];
            NSString *postLength = [NSString stringWithFormat:@"%d", [post length]];
            NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:serverAddress]];

            [request setHTTPMethod:@"POST"];
            [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
            [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
            [request setHTTPBody:post];
            [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
            [request setTimeoutInterval:30];
            NSOperationQueue *queue = [[NSOperationQueue alloc] init];
            [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse* theResponse, NSData* theData, NSError* error){
                //Do whatever with return data

                NSString *result = [[NSString alloc] initWithData:theData encoding:NSUTF8StringEncoding];
                NSLog(@"Result : %@",result);
            }];

I want to retrive that array in PHP. How can I do that?

Here is the php which I tried but returns null:

$handle = fopen('php://input','r');
$jsonInput = fgets($handle);
// Decoding JSON into an Array
$decoded = json_decode($jsonInput,true);

echo json_encode($decoded);

回答1:

I use a slightly different Content-Type (which shouldn't matter):

[request addValue:@"text/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];

And I use a slightly different PHP, too:

<?php

$handle = fopen("php://input", "rb");
$http_raw_post_data = '';
while (!feof($handle)) {
    $http_raw_post_data .= fread($handle, 8192);
}
fclose($handle); 

$json_data = json_decode($http_raw_post_data, true);

echo json_encode($json_data);

?>

If you're getting a blank response, I'd wager you have some PHP error. I'd you check out your server's error log, or temporarily changing the display_errors setting in your php.ini as follows:

display_errors = On