PHP:将文件作为stdin传递给脚本

时间:2016-10-29 00:34:07

标签: php pipe stdin php-7

我正在尝试为我正在构建的电子邮件解析器编写一些测试并且无法开始。

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

我的测试开始时是这样的:

#!/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}");

使用脚本,传递给stdin的唯一内容是测试电子邮件的路径。当我使用file_get_contents时,我得到:

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

TestEmailContents是原始电子邮件文件的内容。我觉得过去使用heredoc运算符以这种方式执行脚本将数据传递给stdin。但在过去的几天里,我一直无法找到任何信息让我超越这个绊脚石。任何建议都会非常值得赞赏!

2 个答案:

答案 0 :(得分:0)

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

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

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

但是,在我的情况下,传入原始电子邮件不需要使用here字符串。无论哪种方式都保留了行结尾。将文件重定向到脚本会产生相同的结果。

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

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

答案 1 :(得分:0)

要在PHP中阅读stdin,您可以使用php://stdin文件名:$content = file_get_contents('php://stdin');$f = fopen('php://stdin', 'r');

要将字符串传递给调用的进程,您有两个选项:popenproc_openpopen功能更易于使用,但使用有限。 proc_open有点复杂,但可以更好地控制stdio重定向。

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

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