mySQL / PHP JSON剥离的特殊字符

时间:2011-01-02 07:45:36

标签: php sql json encoding special-characters

我有一个简单的PHP脚本从mySQL数据库中提取数据并将其编码为JSON。问题是从JSON响应中删除了特殊字符(例如德语ä或ß字符)。在任何单个字段的第一个特殊字符之后的所有内容都被剥离。

字段设置为utf8_bin,在phpMyAdmin中字符显示正确。

PHP脚本如下所示:

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

$con = mysql_connect('database', 'username', 'password');
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("sql01_5789willgil", $con);

$sql="SELECT * FROM weightevent";

$result = mysql_query($sql);
$row = mysql_fetch_array($result);

$events = array();

while($row = mysql_fetch_array($result))
{
 $eventid = $row['eventid'];
 $userid = $row['userid'];
 $weight = $row['weight'];
 $sins = $row['sins'];
 $gooddeeds = $row['gooddeeds'];
 $date = $row['date'];
 $event = array("eventid"=>$eventid, "userid"=>$userid, "weight"=>$weight, "sins"=>$sins, 
 "gooddeeds"=>$gooddeeds, "date"=>$date);
 array_push($events, $event);
}

$myJSON = json_encode($events);

echo $myJSON;

mysql_close($con);
?>

示例输出:

[{"eventid":"2","userid":"1","weight":"70.1","sins":"Weihnachtspl","gooddeeds":"situps! lots and lots of situps!","date":"2011-01-02"},{"eventid":"3","userid":"2","weight":"69.9","sins":"A second helping of pasta...","gooddeeds":"I ate lots of salad","date":"2011-01-01"}]

- &GT;在第一个记录中,字段'sins'的值应该是“Weihnachtsplätzchen”。

非常感谢!

1 个答案:

答案 0 :(得分:3)

在mysql_connect之后

mysql_set_charset("utf8");