简体   繁体   中英

What is the best way to put a Json string in a html tag?

What is the best way to put a json string (encoded php array) into an html tag?

<?php
$content = array(key1=>'value 1', key2=>'value 2');
?>
<span class="someclass" data="<?php echo(json_encode($content)); ?>">Stuff Here</span>

This isn't valid because when it's encoded it will contain speech marks which break the html.

If I used the php function htmlentities would this be enough or could there still be some characters that would break it?

Thanks.

You could use base64 encoding, which can be easily decoded by every language you'd wish to use (like javascript):

<span class="someclass" data="<?php echo base64_encode (json_encode ($content)); ?>">Stuff Here</span>

It only uses az, AZ and 0-9.

Don't put it into a data attribute. It's easier to generate a javascript variable like

<script>
    var data = <?php echo json_encode() ?>
</script>

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