I am playing with an api that just reads from my database and returns the data in json format.
In phpMyAdmin the sentences are perfect (I used utf8_general to input a csv). Example:
A line that uses 'r and special chars etc
But when I echo the json, I get this:
A line that uses ///\\/\/\/r and special chars etc
First I got null object back so I used:
mysql_set_charset('utf8', $link);
But I still get the corrupted data back.
Update:
Some more info:
mysql_set_charset('utf8',$link);
/* grab the posts from the db */
$query = "SELECT * FROM huren WHERE 1";
$result = mysql_query($query,$link) or die('Errant query: '.$query);
// check row count
$amount = mysql_num_rows($result);
/* create one master array of the records */
$houses = array();
if(mysql_num_rows($result)) {
while($post = mysql_fetch_assoc($result)) {
$houses[] = $post;
}
}
/* output in necessary format */
header('Content-type: application/json');
$changed_json= str_replace('\\/', '/',json_encode(array('House'=>$houses)));
echo str_replace('\\\\', '\\',$changed_json);
What’s with the replacing operations?
json_encodeeither returns fully valid JSON representing the exact input you gave it, or it returnsNULLbecause there were issues like your data not being in UTF-8. You should not do anything to the string returned byjson_encode! If you didn’t getNULL, then you have won and just need to echo it.It will just work with this:
The charset doesn’t really matter, since by default,
json_encodeproduces pure ASCII output. This is because by default, unicode characters are represented in unicode escape sequences, e.g.\uxxxx