Reputation: 1550
I am having a users table with Collation as utf8_general_ci. Having fields like name, age, phone and email.
It seems some of the rows of name field is having some trailing spaces. If echo-ed echo "selectedUser " . $selectedUser->name
; It is printing that name with spaces and I just copied the name from DB field and pasted it on a php file, and echo-ed that text, it was printing like
selectedUser "Rohan Harish Reddy\u00a0\u00a0"
name field contains only trailing white-spaces on the field, I am not sure
why it is printed like this ? Why it is not working for json_encode ? How can I convert this user object with json_encode ?
Code:
$users = $stmt->fetchAll(PDO::FETCH_OBJ);
foreach ($users as $user) {
$selectedUser = $user;
echo "selectedUser " . json_encode($selectedUser);
}
If add below code above the fetch all statement, It is working fine.
$this-> adminConn ->query("SET NAMES utf8");
$stmt = $this-> adminConn ->query($sql);
Do I need to set "SET NAMES utf8" for each query ? Is there a common way to achieve it ?
Upvotes: 1
Views: 145
Reputation: 198304
Because you don't have spaces (Unicode 0x0020), you have non-breaking spaces (Unicode 0x00A0). JSON standard (RFC 7159) declares that all Unicode characters may be escaped, and json_encode
is using this to escape the non-breaking spaces (to distinguish them to a human reader from normal spaces, I would assume). The solution is probably to figure out why you have trailing non-breaking spaces in your data.
Upvotes: 1