PHP: 将文件作为标准输入传递到脚本中

PHP: Pass file into script as stdin

我正在尝试为我正在构建的电子邮件解析器编写一些测试,但开始时遇到了问题。

对于正常操作,电子邮件将通过管道传输到脚本,但对于测试,我想模拟管道操作:)

我的测试是这样开始的:

#!/opt/php70/bin/php
<?php

define('INC_ROOT', dirname(__DIR__));

$script = INC_ROOT . '/app/email_parser.php';

//$email = file_get_contents(INC_ROOT . '/tests/test_emails/test.email');
$email = INC_ROOT . '/tests/test_emails/test.email';

passthru("{$script}<<<{$email}");

按原样使用脚本,唯一传递给标准输入的是测试电子邮件的路径。当使用 file_get_contents 我得到:

sh: -c: line 0: syntax error near unexpected token '('
sh: -c: line 0: /myscriptpath/app/email_parser.php<<<TestEmailContents

其中 TestEmailContents 是原始电子邮件文件的内容。我觉得我过去曾使用 heredoc 运算符将数据传递到标准输入以这种方式执行过脚本。但是在过去的几天里,我一直无法找到任何信息来让我克服这个绊脚石。任何建议将不胜感激!

遇到的语法错误就是这样。要获取文件内容并将其作为此处字符串传递,我需要对字符串进行单引号:

$email = file_get_contents(INC_ROOT . '/tests/test_emails/test.email');

passthru("{$script} <<< '{$email}'");

但是,在我的例子中,传递原始电子邮件不需要使用此处字符串。行尾以任何一种方式保留。将文件重定向到脚本会产生相同的结果。

$email = INC_ROOT . '/tests/test_emails/test.email';

passthru("{$script} < {$email}");

要读取 PHP 中的标准输入,您可以使用 php://stdin 文件名:$content = file_get_contents('php://stdin');$f = fopen('php://stdin', 'r');.

要将字符串传递给调用的进程,您有两个选择:popen or proc_openpopen 函数更容易使用,但使用范围有限。 proc_open 有点复杂,但可以让您更好地控制 stdio 重定向。

这两个函数都为您提供了可以使用 fwritefread 的文件句柄。在你的情况下,popen 应该足够好(简化):

$f = popen('./script.php', 'w');
fwrite($f, file_get_contents('test.email'));
pclose($f);