I get content of a html file:
ob_start();
include ("myFile.html");
$html = ob_get_contents();
Now I would like to send $html as plain text via mail to show the code.
I tried "<pre>".$html."</pre>"
and "<code>".$html."</code>"
But I get not the plain code. Can you help me?
Try something like:
<?php
$filePath = __DIR__ . '/myFile.html';
$content = file_get_contents($filePath);
// Escape.
$content = htmlspecialchars($content);
// Makes lines visible.
$content = preg_replace('/\n/', '<br>' . PHP_EOL, $content);
echo $content;
Note that I use single-quotes to improve performance slightly, but when using double-quote, the pattern would be
"/\\n/"
(to escape Back-slash, but should work even without escaping).
I know Top-Master answered this question, but this is an alternative method, that still uses include
. I didn't know enough about PHP to know about the fancy methods, that are probably much more secure.
The <pre>
tag doesn't guarantee that the contents will be displayed verbatim. For example <pre><a>Hello</a></pre>
will show up as Hello, not <a>Hello</a>. To solve this you can use < (less than sign) and &rt; (greater than sign). If you need and actual ampersand ("&"), you can use &.
This modified version should escape <, >, and &. Do not rely on this in terms of security.
ob_start();
include ("myFile.html");
$html = ob_get_contents();
$html = str_replace("&", "&". $html);
$html = str_replace("<", "<". $html);
$html = str_replace(">", ">", $html);
$html = str_replace("\n", "<br/>");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With