如何忽略php包含的第一行?

如何忽略php包含的第一行?

问题描述:

I have a php script, which can be run independently from the command line, so it's first line is #!/usr/bin/env php. However, I also have another script, which can automatically run the first one. It does this by calling include 'example.php', which works, except that it outputs the first line as text.

How do I make include skip the first line? So far the only options I could think of were to wrap the whole thing in an output buffer and then trim the first line, but that has a whole host of problems with it. Alternatives such as using exec() to simulate running the second script from the command line, or reading in the whole file and evaluating it with eval(), both seem like pretty horrible solutions.

Is there any way to tell php, "include this file but don't output the first line"?

I am aware I can just remove the shebang and run the script with php script.php whenever I need to use it, which is ok in this specific case, but I would still like to know if there is an alternative, general way to make include ignore the first (or first X) lines.

我有一个php脚本,它可以独立于命令行运行,所以它的第一行是 #!/ usr / bin / env php code>。 但是,我还有另一个脚本,它可以自动运行第一个脚本。 它通过调用 include'example.php' code>来实现这一点,除了它将第一行作为文本输出之外。 p>

如何使包含跳过 第一行? 到目前为止,我能想到的唯一选择是将整个事物包装在输出缓冲区中然后修剪第一行,但这有很多问题。 替代方法,比如使用 exec() code>来模拟从命令行运行第二个脚本,或读入整个文件并使用 eval() code>进行评估,两者看起来都很漂亮 可怕的解决方案。 p>

有没有办法告诉php,“包含这个文件但不输出第一行”? p>

我知道 我可以删除shebang并使用 php script.php code>运行脚本,只要我需要使用它,这在特定情况下是可以的,但我仍然想知道是否有替代方案, 一般的制作方法包括忽略第一行(或第一行)。 p> div>

IMO a script with a shebang is very explicitly a "front end" to the command line and should not be included in other scripts in the first place, because it contains code specific to dealing with CLI interaction (parsing passed arguments and such). It would probably make more sense to separate the reusable code in that script out into a library file, then include that file from both the shebang script and the other script.

I.e., instead of:

foo.php:

#!/usr/bin/php
// some code

bar.php:

include 'foo.php';

you do:

lib.php:

// some code

foo.php:

#!/usr/bin/php
include 'lib.php';

bar.php:

include 'lib.php';

No. Include/Require technicaly say, execute, no (extra) evaluation.

Your Solution should be the other way:

  • PHP File
  • Bashscript which execute PHP File.

exec() is the right solution. But even better change your understanding of scripting.

Your command line executable is basicly a controller, which says what to execute. Your command line script might be as simple as:

#!/usr/bin/env php
<?php
require_once('classes/DoThing.php');

array_shift($argv);
DoThing::run($argv);

Then you don't need to include or exec() the command line script, just use the class.

ob_start();
include $file;
$stdout = ob_get_contents(); // shebang line will be there
ob_end_clean();