开发者

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.

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?

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.

开发者_如何学C

Sorry if this is really easy. I'm just starting out with PHP.


Use htmlspecialchars on it:

<?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 &amp;
  • " to &quot;
  • < to &lt;
  • > to &gt;

This means that you can safely inject them into your HTML and the tags will appear as plain text.


You need to call htmlspecialchars to HTML-escape the source.


<?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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜