简体   繁体   English

如何让php脚本为包含文件的每一行添加一个选项卡?

[英]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. 在我的HTML中,我有一个包含文件的php脚本。 At that point, the code is indented 2 tabs. 此时,代码缩进了2个选项卡。 What I would like to do is make the php script add two tabs to each line. 我想做的是让php脚本为每一行添加两个选项卡。 Here's an example: 这是一个例子:

Main page: 主页:

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

And "test.inc": 并且“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. 但是,VS在格式化文档时会继续删除它们。

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. 在test.inc文件中,您可以使用输出缓冲来捕获PHP脚本的所有输出,然后再将其发送到浏览器。 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). 您可能最好重新格式化输出,或者使用某种形式的自定义“打印”包装器来标记事物(并使用heredocs打印来获得持续的HTML输出)。

Edit: Use str_replace, as suggested by comment 编辑:使用str_replace,如评论所示

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. 您可以考虑使用HTML Tidy清理源代码,然后再将其呈现给客户端。 There are good tutorials for it on the internet. 互联网上有很好的教程

最简单的解决方案是将前导选项卡添加到包含文件,但不使用文字选项卡,而是使用\\t转义序列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM