MATLAB: Wants to execute matlab file with php

image processingPHP

how to pass php dynamic file path to matlab(any function where I can execute matlab file code). Want to show the output on browser. SO, how can I code for this.

Best Answer

exec or system commands of PHP with matlab -r would be an answer to call MATLAB scripts from PHP. Detail of the integration depends on your MATLAB scripts, but there's no MATLAB interface for PHP, so you need to pass MATLAB calculation results to PHP via File I/O in the following simple example, result of magic square is written in result.csv and will be loaded in PHP and shown in Web browser. matlab command line options are different among Windows, Linux and Mac, for example, -nodesktop option is available in Linux, but for Windows, -automation option is available. So, MATLAB command line string in PHP will be different depending on OS.
magicSquare.m
function out = magicSquare(n)
if ischar(n)
n = str2num(n);
end
out = magic(n);
csvwrite('result.csv', out);
sample.php (Linux version)
<!DOCTYPE html>
<html>
<head>
<title>PHP Test</title>
<meta charset="utf-8">
</head>
<body>
<?php
// Get current working directory
// magicSquare.m exists in this directory
$pwd = getcwd();
// Set command. Please use -r option and remember to add exit in the last
$cmd = '/usr/local/MATLAB/R2017b/bin/matlab -nosplash -nodesktop -sd ' . $pwd . ' -r "magicSquare(5);exit" -logfile log.txt';
// exec
$last_line = exec($cmd, $output, $retval);
if ($retval == 0){
// Read from CSV file which MATLAB has created
$lines = file('result.csv');
echo '<p>Results:<br>';
foreach($lines as $line)
{
echo $line.'<br>';
}
echo '</p>';
} else {
// When command failed
echo '<p>Failed</p>';
}
?>
</body>
</html>
sample.php (Windows version)
<!DOCTYPE html>
<html>
<head>
<title>PHP Test</title>
<meta charset="utf-8">
</head>
<body>
<?php
// Get current working directory
// magicSquare.m exists in this directory
$pwd = getcwd();
// Set command. Please use -r option and remember to add exit in the last
$cmd = 'C:\MATLAB\R2017b\bin\matlab -automation -sd ' . $pwd . ' -r "magicSquare(5);exit" -wait -logfile log.txt';
// exec
$last_line = exec($cmd, $output, $retval);
if ($retval == 0){
// Read from CSV file which MATLAB has created
$lines = file('result.csv');
echo '<p>Results:<br>';
foreach($lines as $line)
{
echo $line.'<br>';
}
echo '</p>';
} else {
// When command failed
echo '<p>Failed</p>';
}
?>
</body>
</html>
Here's result of PHP shown in web browser.
Hope this help.
Related Question