【问题标题】:exec command returning empty arrayexec 命令返回空数组
【发布时间】:2015-07-31 20:43:36
【问题描述】:

我已经在我的 CentOS VPS 中安装了库 wkhtmltopdf link,当我使用终端从我的服务器运行它时:“wkhtmltopdf https://www.google.comgoogle.pdf”我在输出中收到一些消息,如下所示:


加载页面 (1/6) 计数页数 (2/6)
解析链接 (4/6)
加载页眉和页脚 (5/6)
打印页数 (6/6) 完成


并创建 PDF。

现在当我将 PHP 与 exec 命令一起使用时:

<?php
$output = shell_exec("/usr/local/bin/wkhtmltopdf https://www.google.com google.pdf");
var_dump($output);
?>

PDF 文件已创建,一切正常,但我得到 NULL 作为 $output 变量的值。为什么 exec 命令的输出不一样?

谢谢

【问题讨论】:

  • 对不起,虽然我不认为你理解我的答案,但我错了,它与使用 shell_exec() 相同,所以我删除了答案。我在我的脚本中正是这样做的(除了我使用的是反引号而不是 shell_exec)所以我现在完全不确定为什么它不适合你。
  • 在阅读 this 时,我想到可能 shell_exec 在您的 php.ini 中被禁用?
  • 我尝试在 exec 脚本 shell_exec("/usr/local/bin/wkhtmltopdf google.comgoogle.pdf 2>&1 &") 的末尾添加“2>&1 &”;和它现在正在运行,请问还有其他建议吗?
  • 我现在真的很困惑——你到底要什么?您所做的只是将错误输出重定向到标准输出并让程序在后台运行?
  • 等等——你问的是shell_execexec之间的区别吗?在这种情况下exec 不返回输出,它允许您将其收集到一个数组中,并将其作为第二个参数...?

标签: php pdf


【解决方案1】:

如果你不想看到NULL 结果,你应该echo output

$output = shell_exec("/usr/local/bin/wkhtmltopdf https://www.google.com google.pdf 2>&1");
echo($output);

由于输出格式看起来很糟糕,也可以清理它:

$output = shell_exec("/usr/local/bin/wkhtmltopdf https://www.google.com google.pdf 2>&1");
$tidyit = preg_replace("/(.[^\[]*\s\d{1,2}%)\s(?<!100%)|([=>\[]*)/","",$output);
$result = preg_replace("/]/","<br>",$tidyit);
echo($result);

结果

Loading pages (1/6) 100%
Counting pages (2/6)
Object 1 of 1 Resolving links (4/6)
Object 1 of 1 Loading headers and footers (5/6)
Printing pages (6/6)
Preparing
Page 1 of 1 Done 

【讨论】:

    【解决方案2】:

    shell_execexec 的不同之处在于shell_exec 的返回值是输出,而exec 只给你最后一行——如果你想使用exec 检索输出,你需要通过在您希望将结果存储在的数组的第二个参数中:

    <?php
    exec("/usr/local/bin/wkhtmltopdf https://www.google.com google.pdf",$output)
    var_dump($output)
    ?>
    

    您也可以使用反引号代替shell_exec

    <?php
    $output = `/usr/local/bin/wkhtmltopdf https://www.google.com google.pdf`;
    var_dump($output);
    ?>
    

    请看PHP Execution Operator:

    PHP 支持一种执行运算符:反引号 (``)。请注意,这些 不是单引号! PHP 将尝试执行 反引号作为 shell 命令;输出将被返回(即,它 不会简单地被转储到输出;它可以分配给一个变量)。 反引号运算符的使用与 shell_exec() 相同。

    附加

    您的代码是正确的,但脚本可能在 wkhtmltopdf 完成之前超时,这意味着它永远不会收到返回值。试试这个来延长 php 的超时时间并给它时间来完成它的 wkhtmltopdf 进程:

    <?php
        set_time_limit(60); // 60 seconds should be long enough to create your pdf
        $output = `/usr/local/bin/wkhtmltopdf https://www.google.com google.pdf`;
        var_dump($output);
    ?>
    

    【讨论】:

    • 你的代码中的exec命令在哪里,输出只会打印变量的内容。
    • 你明白我写的吗?如果我使用你回答的代码,我将得到的只是输出变量的内容作为输出,你为什么在响应中删除 shell_exec?
    • 哎呀 - 脸红了 - 我的答案与使用 shell_exec() 相同!
    • 我已经更新了这个答案 - 我希望你所追求的东西在某个地方
    猜你喜欢
    • 2014-11-10
    • 1970-01-01
    • 2018-11-29
    • 2019-07-06
    • 2012-10-30
    • 1970-01-01
    • 1970-01-01
    • 2017-01-19
    • 1970-01-01
    相关资源
    最近更新 更多