Reputation: 165
I have a php script that sends 3 values per parameter for a script R.
$typeOfData = 1;
$month = 2;
$year = 2014;
exec("Rscript C:/xampp/R-script/plot.R $typeOfData $month $year", $response);
var_dump($response);
And a R script that receives these parameters.
library(rjson)
args <- commandArgs(TRUE)
tmp <- strsplit(args, " ")
typeOfData <- tmp[[1]][1]
month <- tmp[[2]][1]
year <- tmp[[3]][1]
output <- list(imgname="imgs/tmax.tiff")
cat(toJSON(output))
When I run the php script the variable $ response does not display the json generated by R, it returns me an empty set. Is there any other way to integrate R and PHP.
Upvotes: 6
Views: 14423
Reputation: 912
Have a look at php-r library on github, it lets you execute R code from PHP (having R interpreter installed on your machine).
Upvotes: 0
Reputation:
There are several options, but one option is to use RApache. Install RApache as indicated in http://rapache.net/manual.html
Set the Apache directive in httpd.conf which will make sure all files under /var/www/brew are parsed as R scripts
<Directory /var/www/brew>
SetHandler r-script
RHandler brew::brew
</Directory>
Make your R script with your API with file name plot.R and put it under the /var/www/brew folder. This R script file can e.g. look as follows:
<%
library(rjson)
args <- GET
tmp <- lapply(args, FUN=function(x) strsplit(x, " "))
typeOfData <- tmp[[1]][1]
month <- tmp[[2]][1]
year <- tmp[[3]][1]
output <- list(imgname="imgs/tmax.tiff")
cat(toJSON(output))
%>
Mark the GET
Now you can call your API from PHP as you would call any other webservice by calling http://localhost/brew/plot.R?typeOfData=1&month=2&year=2014
. Replace localhost with the IP of the server where you are hosting the API.
When using RApache, each time you get GET, POST, COOKIES, FILES, SERVER
variables which were passed on to the API call. So if you want to use POST in your call instead of the GET example, go ahead. See the documentation in http://rapache.net/manual.html for these variables.
This is almost the same answer as indicated here: What's the easiest way to deploy an API incorporating R functions?
Upvotes: 9
Reputation: 7592
Check out Rserve-php. It uses Rserve as a backend which is a TCP/IP server for R.
Upvotes: 1