[英]JSON-data from iOS into PHP-script
如何在php脚本中访问json数据,它是通过http-post收到的? 我正在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确实有效。
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"];
此代码可用于发送响应
在PHP脚本中,您可以获取POST数据
json_decode($data);
这将为您提供一个可以使用的对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.