php - R 和 PHP 之间的集成

标签 php r ubuntu

我有一个 php 脚本,它为脚本 R 的每个参数发送 3 个值。

$typeOfData = 1;
$month = 2;
$year = 2014;

exec("Rscript C:/xampp/R-script/plot.R $typeOfData $month $year", $response);

var_dump($response);

以及接收这些参数的 R 脚本。

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

当我运行 php 脚本时,变量 $ response 不显示 R 生成的 json,它返回一个空集。有没有其他方法可以集成 R 和 PHP。

最佳答案

有多种选择,但一种选择是使用 RApache。 按照 http://rapache.net/manual.html 中的指示安装 RApache

在 httpd.conf 中设置 Apache 指令,这将确保/var/www/brew 下的所有文件都被解析为 R 脚本

<Directory /var/www/brew>
    SetHandler r-script
    RHandler brew::brew
</Directory>

使用文件名为 plot.R 的 API 制作 R 脚本,并将其放在/var/www/brew 文件夹下。这个 R 脚本文件可以,例如如下所示:

<%
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))
%>

标记GET

现在您可以通过调用 http://localhost/brew/plot.R?typeOfData=1&month=2&year=2014 调用任何其他网络服务,从 PHP 调用您的 API。将 localhost 替换为您托管 API 的服务器的 IP。

当使用 RApache 时,每次您获得传递给 API 调用的 GET、POST、COOKIES、FILES、SERVER 变量。因此,如果您想在调用中使用 POST 而不是 GET 示例,请继续。请参阅 http://rapache.net/manual.html 中的文档对于这些变量。

这几乎与此处指示的答案相同:What's the easiest way to deploy an API incorporating R functions?

关于php - R 和 PHP 之间的集成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22017258/

相关文章:

r - 如何在 R 中更快地生成随机数?

bash - 如何删除 Sublime Text 2 使用的现有符号链接(symbolic link)?

linux - 在/目录中意外使用 rm -r * 后恢复 ubuntu

php - 更新查询不更新表中的字段

php - 在 codeigniter 中不存在类 : Commonlib is library file

php - 警告 : stream_socket_client(): unable to set private key file

ubuntu - 像设置一样将 Ubuntu 10.04 服务器剥离到 JeOS?

php - 在 fosuserbundle 中添加自定义字段

r - 匹配 %in% 的行为

r - 使用用户定义的颜色修改 networkD3 sankey 图