Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto-indent HTML Code and Display It

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>
like image 747
Teno Avatar asked Jan 22 '26 05:01

Teno


2 Answers

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>";
?>
like image 178
rubo77 Avatar answered Jan 24 '26 17:01

rubo77


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>";
like image 20
niennte Avatar answered Jan 24 '26 17:01

niennte



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!