I managed to create a simple PY () function for PHP that allows you to practically embed python code in your PHP script. You can also pass some input variables to the python process. You cannot return the data, but I believe that this can be easily eliminated :) It is not suitable for use in web hosting (potentially dangerous, system () call), I created it for PHP-CLI, but I can work fine anyway.
<?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"; ?>
source share