0

在我的 ios 应用程序代码中,我在 HTTPBody 中传递了一个 NSDictionary,因此我的 php 可以检查用户是否存在于数据库中。

-(void)checkUser
    {
      NSDictionary *userDict = [NSDictionary dictionaryWithObjectsAndKeys:
      sessionId, @"sessionId",
      sessionName, @"sessionName",
      nil];

      NSData *jsonData = [NSJSONSerialization dataWithJSONObject:userDict
                        options:NSJSONWritingPrettyPrinted error:nil];
      NSString *jsonString = [[NSString alloc] initWithData:jsonData
      encoding:NSUTF8StringEncoding];

      // initialize and open the stream
      NSURL *url = [NSURL URLWithString:@"http://www.mysite.com/userValidate.php"];
      NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
      [request setHTTPMethod:@"POST"];
      [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
      [request setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];

      [NSURLConnection connectionWithRequest:request delegate:self];
    }

在我使用的 PHP 文件中

$raw = file_get_contents('php://input');

回来

post = "{\n \"sessionId\" : \"132156\",\n \"sessionName\" : \"My Name\"\n}";

我关注了这篇文章https://stackoverflow.com/a/5078426/1333294并将此方法添加到我的 PHP 文件中

    function getTestPostData()
    {
     $post_data = explode( "\n", file_get_contents('php://input') );
     $result = array();

     foreach( $post_data as $post_datum ) {
         $pair = explode(":", $post_datum );
         $result[urldecode($pair[0])] = urldecode($pair[1]);
       }
     return $result;
    }

现在我得到

    explode = {
        " \"sessionId\" " = " \"132156\",";
        " \"sessionName\" " = " \"My Name\"";
        "{" = "";
        "}" = "";
    };

我怎样才能进一步“清理”阵列,这样我的阵列就会像

        "sessionId" = "132156";
        "sessionName" = "My Name";

谢谢

4

1 回答 1

0

它看起来像一个 json 数组。尝试将绳子送入json_decode()

function getTestPostData()
{
    $post_data = file_get_contents('php://input');
    $result = json_decode( $post_data, true );
    return $result;
}

这可以进一步减少,但为了清楚起见,请使用您的原始变量。

编辑:添加了第二个参数,以返回数组与对象

于 2013-04-09T11:12:32.993 回答