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.
您需要调用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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.