Executing Python Script in PHP and Exchanging Data Between the Two

executing Python script in PHP and exchanging data between the two

You can generally communicate between languages by using common language formats, and using stdin and stdout to communicate the data.

Example with PHP/Python using a shell argument to send the initial data via JSON

PHP:

// This is the data you want to pass to Python
$data = array('as', 'df', 'gh');

// Execute the python script with the JSON data
$result = shell_exec('python /path/to/myScript.py ' . escapeshellarg(json_encode($data)));

// Decode the result
$resultData = json_decode($result, true);

// This will contain: array('status' => 'Yes!')
var_dump($resultData);

Python:

import sys, json

# Load the data that PHP sent us
try:
data = json.loads(sys.argv[1])
except:
print "ERROR"
sys.exit(1)

# Generate some data to send to PHP
result = {'status': 'Yes!'}

# Send it to stdout (to PHP)
print json.dumps(result)

How to transfer data between Python and PHP

This code does the trick.

Python

import json
data = {'fruit':['oranges', 'apples', 'peaches'], 'age':12}
with open('data.json', 'w') as outfile:
json.dump(data, outfile)

PHP

<?php
$string = file_get_contents("data.json");
$json_a = json_decode($string, true);
echo $json_a['age']; # Note that 'fruit' doesn't work:
# PHP Notice: Array to string conversion in /var/www/html/JSONtest.php on line 4
# Array
?>

This method only works with strings, but it does solve my problem, and I can get around not using lists/arrays.

Pass the data between PHP and Python Script

In PHP you can do something like:

<?php
$start_date = "2019-04-26";
$end_date = "2019-04-30";
$command = "/path/to/script/script.py -s $start_date -e $end_date";
exec($command);
?>

AND Python Script:

import sys
count = 0
for arg in sys.argv:
if arg == "-s":
START = sys.argv[count+1]
elif arg == "-e":
END = sys.argv[count+1]
count+=1
# Here you will get your START & END date.

Sending output of python to PHP webpage

The easiest way is to call the python script via a shell_exec.

Something like this

<?php
echo shell_exec("python /path/to/your/python/script.py");

Run python script by PHP from another server

First option: (Recommended)
You can create the python side as an API endpoint and from the PHP server, you need to call the python API.

Second option:
You can create the python side just like a normal webpage and whenever you call that page from PHP server you pass the params along with HTTP request, and after receiving data in python you print the data in JSON format.



Related Topics



Leave a reply



Submit