Special characters stripped by mySQL/PHP JSON
Posted
by
Will Gill
on Stack Overflow
See other posts from Stack Overflow
or by Will Gill
Published on 2011-01-02T07:45:35Z
Indexed on
2011/01/02
7:53 UTC
Read the original article
Hit count: 273
Hi,
I have a simple PHP script to extract data from a mySQL database and encode it as JSON. The problem is that special characters (for example German ä or ß characters) are stripped from the JSON response. Everything after the first special character for any single field is just stripped.
The fields are set to utf8_bin, and in phpMyAdmin the characters display correctly.
The PHP script looks like this:
<?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);
?>
Sample output:
[{"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"}]
--> in the first record the value for field 'sins' should be "Weihnachtsplätzchen".
thanks very much!
© Stack Overflow or respective owner