首页 > 解决方案 > PHP -- 运行 shell_exec() 不会返回所有输出

问题描述

我正在使用pdfgrep在 PDF 文档中搜索关键字的所有外观。

现在,我想通过 PHP 执行此操作,以便可以在我的网站中使用它。

但是,当我运行时:

$output = shell_exec("pdfgrep -i $keyword $file");
$var_dump($output);

$keyword关键字在哪里$file,文件在哪里,我没有得到整个输出。

PDF 由产品代码、产品名称和产品价格表组成。

当我通过终端执行命令时,我可以看到整行数据:

product code 1    product name with keyword substring    corresponding price
product code 2    product name with keyword substring    corresponding price
product code 3    product name with keyword substring    corresponding price

但是,当我通过 PHP 运行它时,我得到了类似的东西:

name with keyword substring with keyword substring product code 1 
product name with keyword substring product name with keyword substring 
corresponding price

它只是没有得到所有的数据。它并不总是能得到产品代码和价格,而且在很多情况下它也没有得到整个产品名称。

我通过浏览器查看输出并输入,header('Content-Type: text/plain');但它只是美化了输出,数据仍然不完整。

我试图通过 Python3.6 运行完全相同的 shell 脚本,这给了我想要的输出。

现在,我尝试通过 PHP 运行相同的 Python 脚本,但仍然得到相同的损坏输出。

我尝试运行一个我知道会返回较短输出的关键字,但我仍然没有得到我需要的整个数据行。

有没有办法可靠地获取shell_exec()命令抛出的所有数据?

是否有可用的替代方法,例如不同的命令,或从服务器运行 Python 脚本(因为 Python 脚本无论如何都没有任何问题)。

标签: phppython-3.xterminalshell-exec

解决方案


我不知道 pdfgrep 是如何工作的,但也许它混合了标准输出和标准错误?无论哪种方式,您都可以使用这样的结构,将输出流捕获到输出缓冲区中,也可以选择将 stderr 混合到 stdout 中:

$mixStdErrIntoStdOut = false;

ob_start();
$exitCode = 0;
if ($mixStdErrIntoStdOut) 
{
    system("pdfgrep -i $keyword $file 2>&1", &$exitCode);
} else {
    system("pdfgrep -i $keyword $file", &$exitCode);
}
$output = ob_get_clean();

var_dump($output);

推荐阅读