exec command returning empty array

时间:2015-07-31 20:43:37

标签: php pdf

I have installed the library wkhtmltopdf link in my CentOS VPS, when I run it from my server using terminal like : "wkhtmltopdf https://www.google.com google.pdf" I get some messages in the output as following :


Loading pages (1/6) Counting pages (2/6)
Resolving links (4/6)
Loading headers and footers (5/6)
Printing pages (6/6) Done


and the PDF is created.

Now when I use PHP with exec command like :

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

the PDF file is created and all seems ok but I get NULL as value of the $output variable. Why is the exec command not giving the same out put?

Thanks

2 个答案:

答案 0 :(得分:2)

shell_exec and exec are different in that shell_exec's return value is the output, whereas exec only gives you the last line - if you want to retrieve output using exec you need to pass in a 2nd parameter of the array you'd like to store the results in:

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

You can also use backticks instead of shell_exec:

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

Please see PHP Execution Operator:

PHP supports one execution operator: backticks (``). Note that these are not single-quotes! PHP will attempt to execute the contents of the backticks as a shell command; the output will be returned (i.e., it won't simply be dumped to output; it can be assigned to a variable). Use of the backtick operator is identical to shell_exec().

Additional:

Your code is correct, but the script is probably timing out before wkhtmltopdf is finished, meaning it never receives the return value. Try this to extend php's timeout and give it time to finish it's wkhtmltopdf process:

<?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);
?>

答案 1 :(得分:1)

如果您不希望看到echo结果,则可能output NULL

$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 
相关问题