1

I have a data array such as

array(
    'question' => 'Title here',
    'options'  => array( 'Option here', 'Option here' )
)

Now, the title/options can have special characters such as "quotes" and also 'single ones', along with maybe/slashes as well or emojis.

Unfortunately, upon adding these to the data and encoding, I can't decode it. Well, rather, WordPress just returns empty.

$encoded = json_encode( $poll_data );
// save, retrieve from DB
$decoded = json_decode( $retrieved );

Above, $retrieved is:

{"question":"This is \"some quotes\" and also \'single quotes\'","options":["Here is an emoji: ud83dude06","With some slashes/too and back\\as well"]}

But $decoded ends up empty/null

I've tried various sorts of add/stipslashes and also htmlspecialentities to no avail

yesbutmaybeno
  • 1,078
  • 13
  • 31
  • You have to escape your backslashes. Have a look here: https://stackoverflow.com/questions/32056940/how-to-deal-with-backslashes-in-json-strings-php – Sindhara Dec 14 '20 at 20:52
  • 1
    Does this answer your question? [How to deal with backslashes in json strings php](https://stackoverflow.com/questions/32056940/how-to-deal-with-backslashes-in-json-strings-php) – Sindhara Dec 14 '20 at 20:52
  • @kuh-chan it actually fail's with just a single ' or double quote, even with no slashes – yesbutmaybeno Dec 14 '20 at 20:53
  • Your example looks fine, if you escape your backslashes: https://3v4l.org/sSn6m (Just the backslash to escape the backslash and the backslash. So you'll need 4 instead of 2 backslashes:) – Sindhara Dec 14 '20 at 20:55
  • Have you tried setting it to UTF-8 before decoding? $var = htmlentities( $retrieved, ENT_QUOTES, "utf-8" ); $decoded = json_decode( $var ); – James Dec 14 '20 at 20:56

1 Answers1

-1

So, this ended up being the proper way to clean the string before json_encode

$data = wp_encode_emoji( addslashes( stripslashes( htmlspecialchars ( $poll_question ) ) ) )
json_encode( $data );

Seems crazy, but it works with quotes, double quotes, slashes, and emojis.

yesbutmaybeno
  • 1,078
  • 13
  • 31