我有一个iPhone应用程序使用JSON形式的NSData对象发出发布请求(下面的代码供参考)。我正在从CLLocation发送GPS坐标,但是想要访问PHP中的各个元素,这样我就可以将它们存储在某个db中(稍后会这样做)。
由于某些原因,我无法找到一种方法来访问PHP中的各个字段,而我或者得到整个数组,或者什么都没有。
Objective-C代码供参考:
NSDictionary *locationDic = [[NSDictionary alloc] initWithObjectsAndKeys:
[NSNumber numberWithDouble:location.coordinate.latitude], @"lat",
[NSNumber numberWithDouble:location.coordinate.longitude], @"long",
[NSNumber numberWithDouble:location.speed], @"speed",
nil];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:locationDic
options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
error:&error];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost/location.php"]];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"postValues" forHTTPHeaderField:@"HTTP_METHOD"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:jsonData];
PHP:
$handle = fopen("php://input", "rb");
$http_raw_post_data = '';
while (!feof($handle)) {
$http_raw_post_data .= fread($handle, 8192);
}
fclose($handle);
$post_data = json_decode($http_raw_post_data,true);
if (is_array($post_data))
{
$response = array("status" => "ok", "code" => 0, "original request" => $post_data);
}
else
{
$response = array("status" => "error", "code" => -1, "original_request" => $post_data);
}
$processed = json_encode($response);
echo $processed;
echo $processed[0];
知道我在这里可能缺少什么吗?
答案 0 :(得分:0)
我比你更简单地获得有效载荷:
$content = file_get_contents('php://input');
$ary = json_decode($content , true);
并在JSON格式良好时获取关联数组。