Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a php script add a tab to every line of an include file?

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.

like image 830
Eric Avatar asked Sep 13 '09 15:09

Eric


2 Answers

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

like image 129
Adam Wright Avatar answered Nov 08 '22 21:11

Adam Wright


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.

like image 26
Scharrels Avatar answered Nov 08 '22 19:11

Scharrels