How can I invoke a PHP script from Perl?


Question

How can I call a PHP script from a Perl script and get its output as a variable?

1
5
3/24/2010 2:43:46 PM

Accepted Answer

Using the backtick operator:

my $phpOutput = `/usr/bin/php-cli your-script.php`;

Note that you may have to edit the path to point to your php executable.

If you want to have the output as a stream you can also open with a pipe (Perl <3):

open PHPOUT, "/usr/bin/php-cli your-script.php|";
while (<PHPOUT>) {
  # do something with the current line $_
}

See perldoc -f open.

5
3/24/2010 2:45:28 PM

It may be easier to distill this into its core problem, how to invoke another program from perl, which is answered in the perlop manpage's info about qx (or look up the perl qx command through some other means). That informs you how to run an external program and get the output, assuming that your PHP script is actually functional when called through the command line (can you run it via php your-php-script.php ?).

If your script is only functional through an HTTP request, then you need to use something like the LWP::UserAgent or WWW::Mechanize to get the content through its URL, similarly to how you would need to use HTTP_Request.php in PHP.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon