问题
I have built a simple site that allows users to share code where the code is saved in the database as HTML. e.g.
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=1024">
<title></title>
</head>
<body id="" class="">
</body>
</html>
The problem I have is showing it on the site for others to see as when I wrap what the database spits out inside <code><pre></pre></code>
it still renders the HTML and doesn't treat it as code to display. I have read that you have to use >
to get around this, but this isn't feasible as the users will be sharing raw code and will not be able to start converting the code to html entities like that! how do i fix this? Thanks.
Here is the code for the form to inserts this into the DB: http://pastebin.com/i3pn2AjT
and this is how I display it currently:
<div class="code">
<pre>
<?php echo get_post_meta($posts_post_id, 'post_code', true); ?>
</pre>
</div>
回答1:
You need to escape the HTML code either at display time or at insert time.
From your previous questions it seems you are using PHP. You can achieve this with htmlentities().
For example:
<code><?php echo htmlentities($userSuppliedHTML, ENT_QUOTES, 'UTF-8'); ?></code>
回答2:
You can try the php function "highlight_string();
" like this:
<?php
highlight_string('<?php phpinfo(); ?>');
?>
It will output the ('input') as a string with colorcoding. check out its php documentation: http://php.net/manual/en/function.highlight-string.php
来源:https://stackoverflow.com/questions/5291536/show-html-as-code