2011-07-08 30 views
2

我喜歡你的博客,通常會發現很多我的問題的答案,但是這次我很掙扎。 我有一個PHP Web服務器,可以根據請求生成JSON輸出。帶有重音字符的JSON PHP和NSURLConnection

另一方面,我有一個iPhone應用程序嘗試使用請求從服務器提取信息。

問題是,任何時候重音字符都從PHP服務器打印出來,答案就像iPhone上的字段一樣。

這是我的PHP代碼:

// Return a dictionary (array of element/values) 
    // Partial code of the PUser class 
function dictionary() 
{ 
    $array = array(); 
    foreach($this->Fields as $field) 
    { 
     $value = $field->GetValor(true); 
     $array[$field->Nome] = utf8_encode($value); // I tried here several encoding methods 
    } 
    return $array; 
} 

// Header 
header('Content-Type: text/html; charset=utf-8', true); 

$sql = "SELECT * FROM users"; 
$query = db_query($sql); 
$nbrows = db_num_rows($query); 

$array = array(); 

$array["Users"] = array(); 
$user = new PUser; 
for($i=0; $i<$nbrows; $i++) 
{ 
    $user->Read($query); 
    $array["Users"][] = $user->dictionary(); 
} 

$json = json_encode($array); 
echo $json; 

在另一方面,我有iPhone的代碼(從網站http://stig.github.com/json-framework/提取):

// User action 
-(IBAction)onRedo:(id)sender 
{ 
    adapter = [[SBJsonStreamParserAdapter alloc] init]; 
    adapter.delegate = self; 

    parser = [[SBJsonStreamParser alloc] init]; 
    parser.delegate = adapter; 
    parser.supportMultipleDocuments = YES; 

    NSString *url = @"http://wy-web-site"; // The web site I am pushing the date from 

    NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:url] 
                cachePolicy:NSURLRequestUseProtocolCachePolicy 
              timeoutInterval:60.0]; 

    connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; 
} 

#pragma mark - 
#pragma mark SBJsonStreamParserAdapterDelegate methods 

- (void)parser:(SBJsonStreamParser *)parser foundArray:(NSArray *)array 
{ 
    [NSException raise:@"unexpected" format:@"Should not get here"]; 
} 

- (void)parser:(SBJsonStreamParser *)parser foundObject:(NSDictionary *)dict 
{ 
    NSLog(@"parser foundObject: %@", dict); 
} 

#pragma mark - 
#pragma mark NSURLConnectionDelegate methods 

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{ 
    NSLog(@"Connection didReceiveResponse: %@ - %@, encoding: %@", response, [response MIMEType], [response textEncodingName]); 
} 


- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{ 
    NSLog(@"Connection didReceiveData of length: %u", data.length); 
    NSString *str = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; 
    NSLog(@"Data: %@", str); 
    [str release]; 

    // Parse the new chunk of data. The parser will append it to 
    // its internal buffer, then parse from where it left off in 
    // the last chunk. 
    SBJsonStreamParserStatus status = [parser parse:data]; 

    if (status == SBJsonStreamParserError) 
    { 
    NSLog(@"%@", [NSString stringWithFormat: @"The parser encountered an error: %@", parser.error]); 
     NSLog(@"Parser error: %@", parser.error); 

    } else if (status == SBJsonStreamParserWaitingForData) 
    { 
     NSLog(@"Parser waiting for more data"); 
    } 
} 

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{ 
    NSLog(@"Connection failed! Error - %@ %@", 
     [error localizedDescription], 
     [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]); 
} 

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{ 
    NSLog(@"Finish loading"); 
} 

那我得到的是: 從PHP服務器:

{"Users":[{"fs_firstname":"Jo\u00e3o","fs_midname":"da","fs_lastname":"Silva"]} 

從iPhone(NSLog)

2011-07-08 12:00:24.620 GAPiPhone[94998:207] Connection didReceiveResponse: <NSHTTPURLResponse: 0x6f458c0> - text/html, encoding: (null) 
2011-07-08 12:00:24.620 GAPiPhone[94998:207] Connection didReceiveData of length: nnn 
2011-07-08 12:00:24.620 GAPiPhone[94998:207] Data: {"Users":[{"fs_firstname":null,"fs_midname":"da","fs_lastname":"Silva","}]} 
2011-07-08 12:00:24.621 GAPiPhone[94998:207] parser foundObject: { 
    Users =  (
      { 
     "fs_firstname" = "<null>"; 
     "fs_midname" = da; 
     "fs_lastname" = Silva; 
    } 
); 
} 

正如我們所看到的,我的編碼在答案中是空的,即使PHP頭部已經在PHP服務器端指定。

謝謝你的所有輸入。

回答

1

您的內容類型標頭指示數據是UTF-8,但您似乎試圖將其解析爲ASCII。

NSString *str = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; 

這樣::

NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 

,如果你改變這個會發生什麼?

+0

謝謝。我試過NSUTF8StringEncoding,結果是一樣的。 –