php - 如何使用 php exec() 在 Linux 中执行命令并将输出绑定(bind)到数组?

标签 php linux exec

我正在 Linux 中使用 PHP exec() 执行egrep。在 Linux 中实际从命令行执行此语句时,输出是文件列表。当我在 PHP 中回显结果时,它只显示输出的最后一行。

我想将此列表绑定(bind)到一个数组,以便我可以在 PHP 中进一步操作它。我尝试使用 array() 将输出绑定(bind)到一个数组,然后使用 print_r 显示它,但它只显示数组中的一项,即最后一行。

最佳答案

Read the manual ,并查看签名:

string exec ( string $command [, array &$output [, int &$return_var ]] )

因此:

$lastLine = exec('ls', $output, $status);
var_dump($output);

这就是你所追求的!

exec 确实返回最后一行输出,但它接受 3 个参数。第二个是对数组的引用(由于某种原因,不需要事先声明,这里不发出任何通知)。第三个是退出状态(有点像在命令/程序在命令行上运行完毕后执行 echo $? 时得到的状态。
引用手册:

If the output argument is present, then the specified array will be filled with every line of output from the command. Trailing whitespace, such as \n, is not included in this array. Note that if the array already contains some elements, exec() will append to the end of the array. If you do not want the function to append elements, call unset() on the array before passing it to exec().

这意味着,exec最佳用途(如获取最多信息)是这样的:

$last = exec('ls -lta', $fullList, $status);
if ($status !== 0)
{
    exit('command didn\'t finish as expected: '.$status);
}
print_r($fullList);

如果这对您来说仍然没有意义,那么 refer to any of the duplicate questions on this site

关于php - 如何使用 php exec() 在 Linux 中执行命令并将输出绑定(bind)到数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18695492/

相关文章:

linux - 80286 机器(或任何没有内存页面机制的机器)是否有可能是 unix 或 linux

ruby-on-rails - 生成不生成代码

android - 如何为 Android 操作系统移植一些 linux 命令?

c - 为什么 ls 不能与 execvp 一起工作?

c - 如何使用execl()函数来执行C程序?

php - 日期减去 1 年?

php - 我想连同 304 响应一起发送哪些 header ?

php - 上传文件表单 - 无法识别 $_FILES 变量

javascript - 通过 PHP 将 mySQL 数据拉入 Javascript 对象数组

java - 使用 Commons Exec 进行上下文相关执行