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.
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&
"
to"
<
to<
>
to>
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.
精彩评论