将HTML显示为代码 [英] Show HTML as code
问题描述
我建立了一个简单的网站,允许用户共享将代码保存在数据库中的代码作为HTML。例如
<!DOCTYPE html>
< html lang =en>
< head>
< meta http-equiv =content-typecontent =text / html; charset = utf-8>
< meta name =viewportcontent =width = 1024>
< title>< / title>
< / head>
< body id =class =>
< / body>
< / html>
我的问题是在网站上显示给别人看,当我包装数据库时吐出在< code>< pre>< / pre>< / code>
里面,它仍然呈现HTML并且不会将其视为要显示的代码。我已经读过,你必须使用& gt;
来解决这个问题,但这是不可行的,因为用户将共享原始代码并且无法开始将代码转换为像这样的html实体!我该如何解决?谢谢。
以下是将表格插入到数据库中的代码: http://pastebin.com/i3pn2AjT
以下是我目前的显示方式:
< ; div class =code>
< pre>
<?php echo get_post_meta($ posts_post_id,'post_code',true); ?>
< / pre>
< / div>
显示时间或插入时间。
从您之前的问题看,您似乎在使用PHP。您可以通过 htmlentities()
实现此目的。
例如:
< code><?php echo htmlentities( $ userSuppliedHTML,ENT_QUOTES,'UTF-8'); ?>< /代码>
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>
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>
这篇关于将HTML显示为代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!