PHP(或PYTHON)将所有包含的文件合并到一个大文件中(递归?)

2024-10-01 04:56:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个使用includes的PHP脚本。包含的文件也有自己的include。 所有文件都在Web服务器上的同一文件夹中。我想一个单独的PHP脚本,将合并所有这些 放到一个PHP文件中。我将为新脚本提供开始处理的文件(例如索引.php以上)。 如何使用PHP实现这一点?例如,假设我有这些文件:

---------------------
index.php
<?php

*other code1*
include 'header.php';
*other code2*

?>

----------------------
header.php
<?php

*other code3*
include 'subheader.php';
*other code4*

?>


----------------------
subheader.php
<?php

*other code5*

?>


The result of the script begining from the index.php would be:

merged_file.php
<?php

*other code1*
    *other code3*
        *other code5*
    *other code4*
*other code2*

?>

也就是说,所有代码都将放在一个大文件中,并以与之前完全相同的顺序执行。在

所以基本上它会遍历脚本,每次它找到一个include,它就会用给定include文件中的相关PHP代码替换include,并且它会替换include中任何include的代码,直到所有代码都合并到一个文件中(递归函数?)在

注意:我希望在文件中返回未解析的PHP代码。在

提前谢谢

编辑:我理解模块化代码通常更好的做法,但这不是我的问题。我在问我怎么才能做到这一点?不是模块化vs 非模块化代码。在


Tags: 文件代码脚本indexinclude模块化headerphp
2条回答

我上面的评论

I think you maybe are confusing include with recursion ? Are you trying to move all code into one file or include only once? I would keep your code seperate, and have includes, its easier in the long run as your code grows (so you don't get stuck with a giant 1 script app)

可能的解决方案

我想你要问的是“我怎么只包含一次文件?”

我会说,更新include文件以进行include_once()调用。因为它不会在您将代码组合在一起时重新包含这些文件。在

这将让你有一个工作的例子,当你冲洗东西,并清理。在

更新答案

好的,根据反馈,如果你想合并所有的文件,你必须经过一个过程,你有一个主要的PHP脚本(或其他语言),它可以

  1. 递归地读取每个*.php文件
  2. 当它碰到includerequire时,它应该打开该文件
  3. 最终将文件解析为文本,然后在一个巨大的文件中输出文本。在

我想这解决了你的问题phpcompiler.org

phc最初支持PHP的include内置编译时处理。启用此功能将在AST中插入include语句来代替include语句。包含的函数、类和接口成为文件顶级范围的一部分。如果phc无法处理include语句(例如,如果找不到该文件),则会发出警告,并保留include语句。在

相关问题 更多 >