2016-07-06 233 views
1

我想在PHP代码中使用Apache Web服务器执行R脚本(名为script.R)。 这里是我的R代码里面:我安装软件包,然后导入数据,那么我可以继续对数据的分类树:使用Apache服务器从PHP执行R脚本

library(lubridate) 
library(plyr) 
library(rpart) 
library(sqldf) 
library(survival) 
library(randomForest) 
library(rpart.plot) 

data=read.table(file = "t.txt",header = T,sep = ";",stringsAsFactors = T) 

input=read.table(file = "file.txt",header = T,sep = ";",stringsAsFactors = T) 

tree=rpart(sat~.,data,method="class") 


png("tree.png", width=1000, height=800, antialias="cleartype") 
plot(tree, uniform=TRUE, 
    main="Classification Tree") 
text(tree, use.n=TRUE, all=TRUE, cex=0.8) 

dev.off() 

我的PHP脚本必须执行该R脚本。它们被放置在 “C:\ Apache24 \ htdocs目录” 与 “file.txt的” 和 “t.txt”

所以我的PHP文件包含在:

<?php 
exec("Rscript script.R", $results); 
print_r($results); 
?> 

,但我得到 “阵列()”

有什么想法?

+1

尝试使用'passthru()'获取所有输出。 'exec()'只返回最后一行:http://php.net/manual/en/function.passthru.php –

+0

同样的结果!它返回“1”。我想这意味着执行工作,但我没有情节(“tree.png”)。 也许R没有安装在服务器上。我怎么能检查它是否? –

回答

1

需要安装R软件包在系统范围内的位置。在我的机器,这需要:

$ sudo R 
> install.packages("Rpkg", lib = "/usr/local/lib/R/site-library/") 

说明

我看你已经安装了几个R包。我猜你已经将它们安装在默认位置,即用户主目录。

因此,如果您尝试从命令行执行的R脚本,像:

$ php foo.php 

你会看到脚本被成功执行(代码假设其余为无bug)和按预期方式调用script.R

但是,当您尝试从apache执行php时,这会失败。原因是因为你已经在家目录中安装了R包,所以他们无法访问到www-data,这是在apache下执行php的用户。

相关问题