如何使用PHP在数组中存储exec()命令的输出

时间:2014-02-04 03:33:04

标签: php arrays

我有一个运行PHP / HTML页面的Linux Web服务器。

我需要保存一个必须解释为数组的输出 -

    exec($instruction);

输出将是

    1 2 5 7 0 5 3 4

我必须能够调出数组中的特定元素

    echo $result[4]

到目前为止,以下尝试均未成功

    $result =exec($instruction); 
    or
    $result = array(exec($instruction));

更新, 到目前为止,我试过这个 -

$result = shell_exec($instruction);
$out = explode(" ",$result);

我得到了预期的输出,但为什么exxplode()不返回单个元素?

Array ( [0] => 1 1 1 2 1 2 0 0 1 1 )

4 个答案:

答案 0 :(得分:11)

根据文档(php.net),exec有一个第二个参数,通过引用传递,称为$ output。所以你可以尝试:

exec($instruction, $results);

然后你可以访问$ results,这将是一个数组,每行作为一个元素。所以:

$results[0]

将输出您的第一行。

答案 1 :(得分:3)

为什么爆炸对我不起作用? 我使用的shell $指令返回“换行符”或“\ n”。我不得不使用“\ n”作为分隔符来拆分字符串。 这对我有用 -

$result = shell_exec($instruction);
$out = explode("\n",$result);

答案 2 :(得分:2)

$result =exec($instruction); 
$result_array=explode(' ',$result);

或只是

$result =explode(' ',exec($instruction));

答案 3 :(得分:0)

我更喜欢使用:

$result = shell_exec($instruction);
$out = explode("\n",$result);

因为shell_exec函数将完整输出作为字符串返回。如果你有多行,你应该使用它。