简体   繁体   English

将html / php代码存储到php变量中

[英]Store html/php code into php variable

What is the best/safest way to store html mark up with php code in it into a php variable? 将php中的php代码标记为php变量的最佳/最安全方法是什么? Or is there a better solution rather than storing it into a variable? 还是有比将其存储到变量中更好的解决方案?

EDIT: Sorry for not including what I am trying to do! 编辑:对不起,不包括我要做什么! I have a an article template that pulls all information (title/date/content/etc) from a database and loads it. 我有一个文章模板,可从数据库中提取所有信息(标题/日期/内容/等)并加载它。 I have a page where you submit an article and what I am trying to do is automate the file creation process. 我有一个页面,您可以在其中提交文章,而我想做的是使文件创建过程自动化。 I want to create a file that is named the title of the article, then write the template code to it (hence the variable containing the template code and using fwrite()). 我想创建一个名为文章标题的文件,然后将模板代码写入其中(因此,包含模板代码并使用fwrite()的变量)。 I know I could just keep the template file on the website and copy it over/rename it, but if someone stumbles upon the template it is a complete mess, and I don't want to store it in plain text either. 我知道我可以将模板文件保留在网站上,然后将其复制/重命名,但是如果有人偶然发现了模板,那将是一团糟,我也不想将其存储为纯文本格式。

I prefer something like this 我喜欢这样的东西

$str = <<<EOD
Example of string with html <div>some sample text</div>
spanning multiple lines <span>span text!</span>
using heredoc syntax.
EOD;

If you're working with a public website, I would not recommend storing things like articles in files on your server. 如果您正在使用公共网站, 则不建议您在服务器上的文件中存储诸如文章之类的内容。 It's messy, security-iffy, memory-inefficient, and otherwise unorthodox. 这是混乱的,安全性差,内存效率低下的,并且是其他非传统的。

This would probably be a great situation in which to use a MySQL database. 使用MySQL数据库可能是一个很好的情况。 I'll assume you know how to work with one using PHP, but let me know if you don't know how. 我假设您知道如何使用PHP进行操作,但是如果您不知道如何使用,请告诉我。

In this way, you could store the HTML in the database using PHP's htmlentities() function: 这样,您可以使用PHP的htmlentities()函数将HTML存储在数据库中:

$var = htmlentities($var, ENT_QUOTES);

This way, all html characters (ex. "<", ">" and quotes as well) are encoded into the database safely. 这样,所有html字符(例如“ <”,“>”和引号)也被安全地编码到数据库中。 For example, 例如,

<strong>Here is HTML</strong> becomes &lt;strong&gt;Here is HTML&lt;/strong&gt; <strong>Here is HTML</strong>变为&lt;strong&gt;Here is HTML&lt;/strong&gt;

That way, if your templates have any HTML, they can be easily and safely retrieved through mysql_query() and displayed. 这样,如果您的模板具有任何HTML,则可以通过mysql_query()轻松安全地检索它们并显示它们。

This will give a cleaner way then EDO... 这将提供比EDO更干净的方式。

<?php ob_start(); ?>
<div>HTML goes here...</div>
<div>More HTML...</div>
<?php $my_var = ob_get_clean(); ?>

我将其存储在文件中,然后当有人想要创建新文章时,将其加载到DOMDocument中 ,替换您需要替换的元素,然后使用DOMDocument :: saveHTML将代码转储到文件中完成=)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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