简体   繁体   中英

Json encoding strings with spaces

I'm working on a metabox class for wordpress, and specifically implementing the Media Uploading introduced in 3.5. To pass options between the metabox class and the media uploader I like to use json. The basic data structure I have is below ( $data_ar ).

Array
(
    [uploader_title] => Upload or choose a video file
    [uploader_button] => Choose
    [allowed_mimes] => Array
        (
            [0] => application/x-shockwave-flash
            [1] => application/pdf
        )

    [show_icon] => 1
    [show_url] => 1
    [show_file_title] => 1
)

The problem is that when doing a simple

echo '<h1 id="stumped" data-stumped="'.json_encode($data_ar).'">test</h1>';

results in the data attribute containing the json being malformed. The problem is the presence of any string within the array with spaces. Wrapping any sting values with spaces in double quotes does not help.

Setting the data attribute via jQuery.data() works perfectly, but I cant use that as I have these form elements as repeaters, and the double jQuery calls breaks the repeaters.

Talk about stumped. Any pointers on where I should be looking to sort this?

Thanks.

Use htmlentities to encode the json. It will encode all the " which was breaking attribute.

echo '<h1 id="stumped" data-stumped="'.htmlentities(json_encode($data_ar)).'">test</h1>';

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