JSON数据从iOS到PHP脚本

我怎样才能访问一个PHP脚本,它通过http-post接收JSON数据? 我在iOS端执行以下操作:

NSData *data = [NSJSONSerialization dataWithJSONObject:object options:0 error:NULL]; NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://example.com/script.php"]]; [req setHTTPMethod:@"POST"]; [req setHTTPBody:data]; [NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&err]; 

我如何在php脚本中访问这些数据? 换句话说,当我在php脚本中调用json_decode(...)时,是什么?

如果你正在用POST方法发送你的JSON,可以通过下面的代码在PHP中接收

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

使用iOS发送的发布请求不适用于$ _POST。 如果使用js发出类似的请求,则post中的json将起作用。

在PHP脚本中,您可以使用POST数据并执行操作

 json_decode($data); 

这会给你一个你可以使用的对象。

 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; [request setHTTPMethod:@"POST"]; [request setHTTPBody: jsonData]; [request setValue:@"text/html" forHTTPHeaderField:@"Content-Type"]; [request setValue:[NSString stringWithFormat:@"%d", [jsonData length]] forHTTPHeaderField:@"Content-Length"]; 

这个代码可以用来发送一个响应