PHP中的变音符号编码错误

时间:2011-11-25 08:36:35

标签: php mysql json character-encoding

我有食谱表:

CREATE TABLE IF NOT EXISTS `RECIPES` (
  `recipes_id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
  `text` varchar(2000) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
  `count_persons` int(11) NOT NULL,
  `duration` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `date` datetime NOT NULL,
  `accepted` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`recipes_id`),
  KEY `recipes_user_fk` (`user_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=44 ;

插入:

(20, 'Hundefutter', 'Dose öffnen', 4, 10, 1, '2011-12-31 23:59:5', 0)

使用php我将其解析为json(getByID):

<?php
header('Content-Type: text/html; charset=utf8');
$id =  $_GET['id'];
include 'db_connect.php';
$arr = array('Data' => null,'Message' => null,'Code' => null);
        if (is_numeric($id))
        {
            //include 'db_connect.php';
            $id =  mysql_real_escape_string($_GET['id']);
            mysql_query("SET NAMES 'utf8'");
            mysql_query("SET CHARACTER SET 'utf8'");
            $sql = "Select * from RECIPES WHERE recipes_id=".$id;
            $result = mysql_query($sql,$db) or exit("QUERY FAILED!");

            while($row = mysql_fetch_array($result))
             {
                 $arr['Data']['Recipes']['Recipe_'.$row['recipes_id']]['ID'] = $row['recipes_id'];
                 $arr['Data']['Recipes']['Recipe_'.$row['recipes_id']]['TITLE'] = $row['title'];
                 $arr['Data']['Recipes']['Recipe_'.$row['recipes_id']]['TEXT'] = utf8_decode($row['text']);
                 $arr['Data']['Recipes']['Recipe_'.$row['recipes_id']]['COUNT_PERSONS'] = $row['count_persons'];
                 $arr['Data']['Recipes']['Recipe_'.$row['recipes_id']]['DURATION'] = $row['duration'];
                 $arr['Data']['Recipes']['Recipe_'.$row['recipes_id']]['USER_ID'] = $row['user_id'];
                 $arr['Data']['Recipes']['Recipe_'.$row['recipes_id']]['DATE'] = $row['date'];
             }
             if(count($arr['Data']['Recipes'])==1)
             {
                $arr['Code'] = 200;

             }
             else
             {
                $arr['Code'] = 404;
                $arr['Message'] = "not found";
             }

        }


        else
        {
                $arr['Code'] = 400;
                $arr['Message'] = "Bad Request";
        }
        mysql_close($db);
        echo json_encode($arr);

?>

我的问题是当我调用getRecipeByID.php?= 20:

  

{ “数据”:{ “配方”:{ “Recipe_20”:{ “ID”: “20”, “TITLE”: “Hundefutter”, “TEXT”:“剂量   \ u00f6ffnen “ ”COUNT_PERSONS“: ”4“, ”DURATION“: ”10“, ”USER_ID“: ”1“, ”日期“:” 2011-12-31   23时59分59秒 “}}},” 消息 “:NULL,” 代码“:200}

我将'ö'作为字母代码。

如何解决这个问题?

由于

1 个答案:

答案 0 :(得分:8)

  

我将'ö'作为字母代码。如何解决这个问题?

你没有。 \u00f6是JSON中完全合法的字符转义码。解析完JSON后,它将被解析为ö