[英]How can I stop the result of file_get_contents [PHP] from being processed as HTML?
I am using the PHP function file_get_contents
to read and display the contents of some .txt
files. 我正在使用PHP函数
file_get_contents
来读取和显示某些.txt
文件的内容。
If the contents of the file is HTML code, how can I display this as a string instead of the page treating it as HTML? 如果文件的内容是HTML代码,我如何将其显示为字符串而不是将其视为HTML的页面?
My current code is something like this: 我目前的代码是这样的:
<?php
$load_desc = file_get_contents(/url/of/my/file.txt);
echo "<div>$load_desc</div>"
?>
which works fine if the file contents is plain text but, for example, if the contents contains <img>
tags, an image will be displayed. 如果文件内容是纯文本,则可以正常工作,但是,例如,如果内容包含
<img>
标签,则会显示图像。
Sorry if this is really easy. 对不起,如果这真的很容易。 I'm just starting out with PHP.
我刚刚开始使用PHP。
Use htmlspecialchars
on it: 在它上面使用
htmlspecialchars
:
<?php
$load_desc = file_get_contents(/url/of/my/file.txt);
echo "<div>" . htmlspecialchars($load_desc) . "</div>"
?>
This converts unsafe characters to their entity references: 这会将不安全的字符转换为它们的实体引用:
&
to &
&
to &
"
to "
"
到"
<
to <
<
to <
>
to >
>
到>
This means that you can safely inject them into your HTML and the tags will appear as plain text. 这意味着您可以安全地将它们注入HTML,并且标记将显示为纯文本。
您需要调用htmlspecialchars
来HTML转义源代码。
<?php
$load_desc = file_get_contents(/url/of/my/file.txt);
header('Content-type: plain/text');
echo "<div>$load_desc</div>"
?>
this will show all content as a plain text. 这会将所有内容显示为纯文本。 but if you need to get rid of the tags or show them as is you can use either
strip_tags
or htmlspecialchars
repsectivly. 但如果您需要删除标签或按原样显示它们,您可以使用
strip_tags
或htmlspecialchars
repsectivly。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.