How to call a Python Script from PHP?
You use the system function: http://php.net/manual/en/function.system.php
Something like this:
$mystring = system('python myscript.py myargs', $retval);
I managed to make simple function PY([parametress], code) for PHP. You may almost include python code to your PHP. You may pass as well some simple input variables to python process. You cannot get any data back, but I believe that could be easily fixed :) Not ok for using at webhosting (potentionally unsafe, system call), I created it for PHP-CLI..
<?php
function PY()
{
$p=func_get_args();
$code=array_pop($p);
if (count($p) % 2==1) return false;
$precode='';
for ($i=0;$i<count($p);$i+=2) $precode.=$p[$i]." = json.loads('".json_encode($p[$i+1])."')\n";
$pyt=tempnam('/tmp','pyt');
file_put_contents($pyt,"import json\n".$precode.$code);
system("python {$pyt}");
unlink($pyt);
}
//begin
echo "This is PHP code\n";
$r=array('hovinko','ruka',6);
$s=6;
PY('r',$r,'s',$s,<<<ENDPYTHON
print('This is python 3.4 code. Looks like included in PHP :)');
s=s+42
print(r,' : ',s)
ENDPYTHON
);
echo "This is PHP code again\n";
?>
You can try this:
python scripts:
test.py: print "hello"
then php Scripts
index.php: $i =`python test.py`; echo $i;