As the main language for web program development, php is widely used. As a statistical software, R has good operability in the implementation of mathematical algorithms. Recently, due to work needs, I have to perform complex mathematical calculations on some web application data. However, although PHP itself can write some mathematical algorithms, it is still difficult to meet the demand. The efficiency of dozens of lines of code is not comparable to a function in R. , after research, it was finally possible to call R for calculation operations in the instant access of PHP, and directly read the calculation results and display them on the web page. The general idea is as follows:

The key point is that php activates the R program to run, passes calculation parameters to R, and obtains results.

To activate R in php, you can use the built-in function exec, so that any command executed in the operating system running window can be executed here. The command executed by R is (the following refers to the windows environment)

"D:\\Program Files\R\R-2.15.2\bin\x64\R.exe" --vanilla < D:\\test.R  out.txt

The first part is the path of the local R program, followed by the option of the R software, which can be customized, followed by the R program file to be executed, which is the key point, and finally the output file is executed. This file is required for the instruction, but it is of no use to us. .

In order to realize each visit to the php page, different R programs are executed due to different parameters. Therefore, the program file name of test.R needs to be generated for each visit to ensure that there is a unique R program file for each visit. Use the form of writing a text file to store parameter names and parameter values, specify the result file name, and specify the activation of the R file in the php page. In this file, you can specify the R program file that calls a complex fixed file name. After running, a unique The result text file, the php file then reads the result of the text file, processes it and displays it, that is, the purpose is achieved.

exec($command,$out1,$out2);

In the php output result, as long as the value of $out2 is 0, the execution is successful.

It should be noted that the backslash used in the file path is a special escape symbol for backslash in PHP. When generating $command, you need to pay special attention to whether the output string meets the requirements. In addition, for file storage, etc., try to use absolute paths.


Leave a Reply