When displaying HTML code in PHP, if I want to indent tags what would be the best way?
For example,
<?php
$html = '<div><p><span>some text</span></p></div>';
echo htmlspecialchars($html);
?>
will give <div><p><span>some text</span</p></div>
.
Instead, I'd like to show something like,
<div>
<p>
<span>some text</span>
</p>
</div>
You can use htmLawed
http://www.bioinformatics.org/phplabware/internal_utilities/htmLawed/
this would be your code:
<?php
require("htmLawed/htmLawed.php");
echo "<pre>";
echo htmlspecialchars(
htmLawed('<div><p><span>some text</span></p></div>', array('tidy'=>4))
);
echo "</pre>";
?>
If you know how you want it to be output (as in what your string will look like as you make it), you can easily do it like this:
$html = "<div>
\t\t<p>
\t\t\t<span>some text</span>
\t\t</p>
\t</div>";
Be sure to use double quotes though, not single ones.
Output as viewed in source code:
<div>
<p>
<span>some text</span>
</p>
</div>
If you want to have it done automatically, then you might have to hold out for another answer, I don't really know much regex to help, and I don't use DOM (not even sure if it is applicable in this situation).
You may need to know PHP Tidy extension.
Tidy is a binding for the Tidy HTML clean and repair utility which allows you to not only clean and otherwise manipulate HTML documents, but also traverse the document tree.
You may also want to use the HEREDOC.
$html = <<<NICE
<div>
<p>
<span>some text</span>
</p>
</div>
NICE;
echo "<pre>";
echo htmlspecialchars( $html );
echo "</pre>";