1

PHPページを介してiOSアプリからmySQLデータベースにJSONデータを送信しようとしています。何らかの理由で、私の POST データが php ページで利用できません。

- (IBAction)jsonSet:(id)sender {   
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@"firstvalue", @"firstkey", @"secondvalue", @"secondkey", nil];
    NSData *result =[NSJSONSerialization dataWithJSONObject:dict options:0 error:&error];
    NSURL *url = [NSURL URLWithString:@"http://shred444.com/testpost.php"];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:[NSString stringWithFormat:@"%d", jsonRequestData.length] forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:jsonRequestData];

    NSURLResponse *response = nil;
    NSError *error = nil;

    NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

phpページが呼び出され、データベースへの書き込みが確認されていることはわかっていますが、

私のphpファイルの最初の数行は、POSTデータを取得します

<?php
// Put parameters into local variables
$email = $_POST["firstkey"];
...

しかし、何らかの理由で、$email も空の文字列です。APIkitchen.com を使用してページをテストし、それが機能することを確認できるため (Content-type フィールドと Content-Length フィールドを除外した場合のみ)、問題は iOS コードにあると感じています。

4

5 に答える 5

2

PHP は、JSON POST 本体を $_POST 配列にデコードしません (したがって、使用できません$email = $_POST["firstkey"];)。受信データを配列 (またはオブジェクト) に抽出する必要があります。PHP ファイルのコード行:

$jsonString = file_get_contents('php://input');
$jsonArray = json_decode($json_string, true);

$jsonArray は、送信した JSON 構造を表します。

于 2012-12-14T21:40:01.740 に答える
1

ヴァレラの答えには小さなタイプミスがあります

$jsonString = file_get_contents('php://input');
$jsonArray = json_decode($jsonString, true);

$email = $jsonArray('firstkey');
于 2013-06-03T10:15:36.267 に答える
1

うまくいくように見えたのはこれでした:

$handle = fopen('php://input','r');
$jsonInput = fgets($handle);
// Decoding JSON into an Array
$decoded = json_decode($jsonInput,true);
于 2012-12-15T06:30:51.623 に答える
0
<?php

$handle = fopen('php://input','r');
$jsonInput = fgets($handle);
$decoded = json_decode($jsonInput,true);
print_r($decoded['firstkey']);

?>
于 2015-09-19T04:54:45.523 に答える