简体   繁体   中英

Wordpress json_encode and json_decode with quotes, slashes, emojis

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM