questions

WordPress json_encode and json_decode with quotes, slashes, emojis

Rate this post

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

 

✔️Solution:

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.

Leave a Reply

Your email address will not be published.

Back to top button