[英]JSON-data from iOS into PHP-script
How can I access json data within a php-script, which it received via http-post? 如何在php脚本中访问json数据,它是通过http-post收到的? I'm doing the following on the iOS-side:
我正在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];
How do I access this data in the php-script? 如何在php脚本中访问此数据? In other words, when I call
json_decode(...)
in the php-script, what is ...
? 换句话说,当我在php脚本中调用
json_decode(...)
时,是什么...
?
If your are sending your JSON in POST method , It can be received in PHP with the below code 如果您使用POST方法发送JSON,可以使用以下代码在PHP中接收它
<?php $handle = fopen('php://input','r');
$jsonInput = fgets($handle);
// Decoding JSON into an Array
$decoded = json_decode($jsonInput,true);
?>
The post request when sent using iOS does not works with $_POST. 使用iOS发送的帖子请求不适用于$ _POST。 If similar request is issued using js the json in post does works.
如果使用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"];
This code can be used to send a response 此代码可用于发送响应
In the php script you take the POST data and do 在PHP脚本中,您可以获取POST数据
json_decode($data);
and that will give you an object you can work with. 这将为您提供一个可以使用的对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.