Reputation: 2632
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>
Upvotes: 2
Views: 8644
Reputation: 27
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>";
Upvotes: 2
Reputation: 20835
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>";
?>
Upvotes: 6
Reputation: 9303
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.
Upvotes: 1
Reputation: 33512
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>\n\t\t<p>\n\t\t\t<span>some text</span>\n\t\t</p>\n\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).
Upvotes: 0