在PHP中检索R输出

Here's the issue:

I am using R to run some statistical analysis. The results of which will eventually be sent to a an embedded swf on the user's client machine.

To do this, I have PHP execute a shell script to run the R program, and I want to retrieve the results of that program so I can parse them in PHP and respond with the appropriate data.

So, it's simply:

$output = shell_exec("R CMD BATCH /home/bitnami/r_script.R");
echo $output;  

But, I receive nothing of course, because R CMD BATCH writes to a file. I've tried redirecting the output in a manner similar to this question which changes my script to

$output = shell_exec('R CMD BATCH /home/bitnami/raschPL.R /dev/tty');
echo $output; 

But what I get on the console is a huge spillout of the source code, and nothing is echoed.

I've also tried this question's solution in my R script.

tl;dr; I need to retrieve the results of an R script in PHP.

Cheers!

Found it, the answer is through Rscript. Rscript should be included in the latest install of R.

Using my code as an example, I would enter this at the very top of r_script.R

#!/usr/bin/Rscript --options-you-need

This should be the path to your Rscript executable. This can be found easily by typing

which Rscript

in the terminal. Where I have --options-you-need, place the options you would normally have when doing the CMD BATCH, such as --slave to remove extraneous output.

You should now be able to run your script like so:

./r_script.R arg1 arg2

Important! If you get the error

Error in `contrasts<-`(`*tmp*`, value = "contr.treatment") : 
could not find function "is" 

You need to include the "methods" package, like so:

require("methods"); 

If it writes to file perhaps you could use file_get_contents to read it?

http://php.net/manual/en/function.file-get-contents.php

Perhaps,a much simpler workaround, would be:

    $output = shell_exec('R CMD BATCH /home/bitnami/raschPL.R > /dev/tty 2>&1');
    echo $output; 

Redirects both STDOUT and STDERR, since R outputs to STDERR, by default.