I want to return the output of a perl script to a webpage. However it only returns the last line.
Perl script:
my $directory = $ARGV[0];
opendir(DIR,$directory);
my @files = grep {/\.txt$/ } readdir(DIR);
closedir(DIR);
foreach(@files) {
print $_."\n";
}
PHP code:
$perl_result = exec("perl $script_folder $project_folder");
*some code*
<?php print $perl_result; ?>
Expected output (and what the script returns in a Linux command line):
test.txt
test2.txt
test3.txt
What PHP returns:
test3.txt
What do I have to change in my code to get PHP to show all lines?
Thanks
Quoting from the PHP manual page for exec()
:
Return Values
The last line from the result of the command. If you need to execute a command and have all the data from the command passed directly back without any interference, use the
passthru()
function.To get the output of the executed command, be sure to set and use the
output
parameter.
So one suggestion is stop using exec()
and start using passthru()
. However, that's nonsense. passthru()
doesn't actually return anything. It may be sufficient if all you need to do with $perl_result
is print it to the browser, and thus don't really need the output to be stored in a variable at all. But if you need to match against the output, or manipulate it in any way, you don't want passthru()
.
Instead, try the backtick operator:
<?php
$perl_result = `perl $script_folder $project_folder`;
Or try setting the second argument of exec()
to an empty array:
<?php
$perl_result = array();
exec("perl $script_folder $project_folder", $perl_result);
$perl_result = implode("\n", $perl_result); # array --> string
From php docs,
Return Values
The last line from the result of the command. If you need to execute a command and have all the data from the command passed directly back without any interference, use the passthru() function.
To get the output of the executed command, be sure to set and use the output parameter
来源:https://stackoverflow.com/questions/21407590/return-perl-output-to-php