如何在PHP中使用UTF-8:json_encode

时间:2015-07-07 05:22:32

标签: php mysql json pdo utf-8

我从MySQL获取数据并使用php以json格式显示,但我的数据是波斯语,它显示?字符而不是原始数据 如下所示。

  

{“allnews”:[{“id”:“35”,“Onvan”:“???? ????? ???????????????????? ??   ????? “},{” ID “:” 36" , “Onvan”:“____ ???? ? ???????????   ?????“},{”id“:”37“,”Onvan“:”??????? ???? ??? ??? ???? ???? ?? ??? ??   ???? ???? ??????? ??? ?????? ???????? ?? “},{”id“:”38“,”Onvan“:”?????   ????????? ???? ??? ?? ?? ??????? ???????? “},{” id为 “:” 39" , “Onvan”:“???   ???? ??? ????“}]}

这是我的代码。请你查看哪里出错了。

<?php
$hostname='localhost';
$username='xxxxxxxxx';
$password='xxxxxxxxx';
$response = array();
try {

    $dbh=new PDO("mysql:host=$hostname;dbname=dbtest",$username  ,$password);

    $response["allnews"] = array();

    /*** QUERY ****/
    $sql='SELECT * FROM test';

    $stmt=$dbh->query($sql);

    $objs = $stmt->fetchAll(PDO::FETCH_OBJ);

    foreach($objs as $object) {
        $news = array();        
        $news["id"]=$object->id;
        $news["Onvan"]=$object->title;

        array_push($response["allnews"], $news);
    }

    echo json_encode($response);

    /*** close connection ***/
    $dbh=null;

}catch(PDOException $e) {
 echo $e->getMessage();
}
?>

3 个答案:

答案 0 :(得分:3)

使用

header("Content-type: application/json; charset=utf-8");

就在

之前
echo json_encode($response);

它也可能是Mysql提取错误

所以替换行

$dbh=new PDO("mysql:host=$hostname;dbname=dbtest",$username  ,$password);

$dbh=new PDO("mysql:host=$hostname;dbname=dbtest;charset=utf8",$username  ,$password);

答案 1 :(得分:2)

最简单的解决方案

-(void)applicationDidEnterBackground {
  [self.locationManager stopUpdatingLocation];

  UIApplication* app = [UIApplication sharedApplication];

  bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
    [app endBackgroundTask:bgTask];
    bgTask = UIBackgroundTaskInvalid;
  }];

  self.timer = [NSTimer scheduledTimerWithTimeInterval:intervalBackgroundUpdate
                                                target:self.locationManager
                                              selector:@selector(startUpdatingLocation)
                                              userInfo:nil
                                               repeats:YES];
}

将charset添加到上面一行,如(mysql:charset = utf8mb4;)

$dbh=new PDO("mysql:host=$hostname;dbname=dbtest",$username  ,$password);

答案 2 :(得分:1)

您可以使用utf8_encode(String)

foreach($objs as $object) {
        $news = array();        
        $news["id"]=utf8_encode( $object->id);
        $news["Onvan"]=utf8_encode( $object->title);

        array_push($response["allnews"], $news);
    }