2013-04-09 46 views
0

在我的iOS应用程序代码中,我传递了一个NSBictionary在HTTPBody 所以我的PHP可以检查用户是否存在于数据库中。PHP break'file_get_contents'into array

-(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文件IM USIG

$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; 
    } 

现在我“M越来越

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

我怎么能 '干净' 的阵列的任何进一步所以我ARRY会像

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

感谢

+0

摆脱一个通过使用'文件爆炸()' – 2013-04-09 11:12:20

+1

你应该'json_decode'那个字符串,*如果它是有效的JSON。 – deceze 2013-04-09 11:12:32

回答

0

它看起来像一个JSON数组。尝试将字符串送入json_decode()

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

这可以进一步减少,但使用原始变量清晰离开。

编辑:添加第二PARAM,给回的阵列VS,而不是`爆炸( “\ n” 个,file_get_contents()函数)`对象

+0

对不起,但即时通讯新的PHP,我需要做像json_decode($ raw = file_get_contents('php:// input')); ? – ItayAmza 2013-04-09 11:14:14

+0

我的Mac决定这是一个很好的时间来暗恋......我会在几分钟内检查它,谢谢 – ItayAmza 2013-04-09 11:21:37

+0

即时通讯使用json_decode()方法时,PHP根本没有返回答案,但它确实当我没有使用它,确实这意味着我没有在我的客观c代码中正确编码json? – ItayAmza 2013-04-09 11:39:51