0

I'm having some troubles with the json_encode/decode functions when i store the string to a MySQL DB table. The problem is in the swedish chars, like ÅÄÖ. If have something like

$my_arr = array('Räksmörgås');
$json = json_encode($my_arr):
print_r(json_decode($json)); 

It works just fine, the trouble is, as i said, when i store the jsonstring to the db and then collects them. The table (entire db) has the encoding 'utf8_general_ci'. I've tried uft8_unicode_ci' as well, with the same result, that the output will be 'Ru00e4ksmu00f6rgu00e5s'. The column where i store this valus is 'TEXT'.

What am i doing wrong?

Edit, i forgot to mention this is a plugin for wordpress and i'm using $wpdb->prepare() and $wpdb->query().

1
  • Make sure the connection to your database is configured as UTF8. E.g. mysql_query("SET NAMES 'utf8'");.
    – Sjoerd
    Mar 18, 2013 at 10:37

2 Answers 2

1

Somewhere in your code you are stripping slashes.

// text: Räksmörgås
// json_encode(): R\u00e4ksm\u00f6rg\u00e5s
// your output: Ru00e4ksmu00f6rgu00e5s
4
  • Hmm. You're right. As i remember json_encode makes it with back-slashes, but the string to the database strips them out! Did not even see this. So, it's something with the $wpdb->prepare i guess.
    – gubbfett
    Mar 18, 2013 at 10:49
  • Yep! when i manually add the back-slash with phpmyadmin the output is correct!
    – gubbfett
    Mar 18, 2013 at 10:51
  • Then your insert is not correct, there is some stripslashes() on insert. Mar 18, 2013 at 10:52
  • i did it like this: str_replace('\\', '\\\\', json_encode($my_arr)); and that works fine. Thanks!
    – gubbfett
    Mar 18, 2013 at 10:55
0

Try to store result in BLOB and not TEXT field. What do you used to store data ? PDO ? Mysqli ? Mysql ?

1
  • Actually, it's a plugin for wordpress. So i use $wpdb->prepare() and $wpdb->query(). I'll try blob!
    – gubbfett
    Mar 18, 2013 at 10:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.