請幫我解決發(fā)布JSON解碼的表情符號的問題.
我有一個UITextView,這個文本視圖可能有一個表情符號字符.我將數(shù)據(jù)發(fā)布到Web服務器,UITextView.text顯示為JSON,問題是當文本有表情符號時,我無法獲取數(shù)據(jù).我所做的是:
$postData = file_get_contents("php://input") to get the data.
然后我用
$post = json_decode($postData,true);
解碼數(shù)據(jù)并具有關(guān)聯(lián)數(shù)組并將數(shù)據(jù)插入數(shù)據(jù)庫.
這是我將數(shù)據(jù)插入數(shù)據(jù)庫時??的代碼段.
$postData = file_get_contents("php://input");//$postData = '{"body":"characters here ","subject":"subject here","username":"janus","from_id":"185","to_id":"62"}'; $post = json_decode($postData,true); $data=array( 'user_id_from'=>mysql_real_escape_string($post['from_id']), 'user_id_to'=>mysql_real_escape_string($post['to_id']), 'subject'=>mysql_real_escape_string($post['subject']), 'message'=>mysql_real_escape_string($post['body'])); $messages_obj->insert($data);
沒有找到表情符號字符,它工作正常.沒問題.問題是當找到表情符號字符時,$post(解碼數(shù)據(jù))中的數(shù)據(jù)為空.
我試圖使用虛擬數(shù)據(jù)(代碼片段中的第2行)
//$postData = '{"body":"characters here ","subject":"subject here","username":"janus","from_id":"185","to_id":"62"}';
我成功地將表情符號字符插入數(shù)據(jù)庫中.我不知道為什么但是當數(shù)據(jù)來自設備時它不同工作($postData = file_get_contents(“php:// input”))
這就是我在客戶端編碼和發(fā)布數(shù)據(jù)的方式.
NSMutableDictionary *messageDetails = [[NSMutableDictionary alloc] init];[messageDetails setObject:[loginItems objectForKey:@"user_id"] forKey:@"from_id"];[messageDetails setObject:recipientID forKey:@"to_id"];[messageDetails setObject:@"subject here" forKey:@"subject"];[messageDetails setObject:newMessageField.text forKey:@"body"]; [messageDetails setObject:[loginItems objectForKey:@"username"] forKey:@"username"];NSString *strPostData = [messageDetails JSONRepresentation];[messageDetails release];NSData *postData = [NSData dataWithBytes:[strPostData UTF8String] length:[strPostData length]];[urlRequest setHTTPMethod:@"POST"];[urlRequest setHTTPBody:postData];
BTW,誰制作了這些表情符號字符?他毀了我的命!
解決方法:
一旦將數(shù)據(jù)發(fā)送到您的php腳本,您需要將其轉(zhuǎn)換為多字節(jié)字符串:
$content = mb_convert_encoding($content, 'UTF-8');
你可以使用這個功能:
function cb($content){ if(!mb_check_encoding($content, 'UTF-8') OR !($content === mb_convert_encoding(mb_convert_encoding($content, 'UTF-32', 'UTF-8' ), 'UTF-8', 'UTF-32'))) { $content = mb_convert_encoding($content, 'UTF-8'); } return $content;}
編輯:數(shù)據(jù)可能是我們的類型application / x-www-form-urlencoded并且該函數(shù)正確轉(zhuǎn)換了它.
來源:http://www.icode9.com/content-1-218501.html