views:

497

answers:

3

Within my HTML, I have a php script that includes a file. At that point, the code is indented 2 tabs. What I would like to do is make the php script add two tabs to each line. Here's an example:

Main page:

<body>
    <div>
     <?php include("test.inc"); ?>
    </div>
</body>

And "test.inc":

<p>This is a test</p>
<div>
    <p>This is a nested test</p>
    <div>
     <p>This is an more nested test</p>
    </div>
</div>

What I get:

<body>
    <div>
<p>This is a test</p>
<div>
    <p>This is a nested test</p>
    <div>
     <p>This is an more nested test</p>
    </div>
</div>
    </div>
</body>

What I want:

<body>
    <div>
  <p>This is a test</p>
  <div>
      <p>This is a nested test</p>
      <div>
       <p>This is an more nested test</p>
      </div>
     </div>
    </div>
</body>

I realise I could just add leading tabs to the include file. However, VS keeps removing those when I format the document.

A: 

The easiest solution is to add leading tabs to the include file, but instead of using literal tabs, use the \t escape sequence.

Isaac Waller
+4  A: 

In your test.inc file, you can use output buffering to capture all the output of the PHP script, before it is sent to the browser. You can then post-process it to add the tabs you want, and send it on. At the top on the file, add

<?php
  ob_start();
?>

At the end, add

<?php
  $result = ob_get_contents();
  ob_end_clean();
  print str_replace("\t" . $result, "\n", "\n\t");
?>

I don't necessarily subscribe to this solution - it can be memory intensive, depending on your output, and will prevent your include file from sending partial results to the client as it works. You might be better off reformatting the output, or using some form of custom "print" wrapper that tabs things (and use printing of heredocs for constant HTML output).

Edit: Use str_replace, as suggested by comment

Adam Wright
+1 But likewise, I really don't see the point in adding the extra TABs. They simply do not contribute in any way to the end result, and they just take up more space in the final rendered HTML
Miky Dinescu
Please don't use `preg_replace()` for that, `str_replace()` is absolutely sufficent.
soulmerge
+1  A: 

I don't think your solution can be done easily. You might consider using HTML Tidy to clean your source code before presenting it to a client. There are good tutorials for it on the internet.

Scharrels
`ob_start('ob_tidyhandler')` at the top of your file should be everything you need. I wouldn't recommend enabling it, when debugging, though.
soulmerge