Pass JSON Data from PHP to Python Script - php

I'd like to be able to pass a PHP array to a Python script, which will utilize the data to perform some tasks. I wanted to try to execute my the Python script from PHP using shell_exec() and pass the JSON data to it (which I'm completely new to).
$foods = array("pizza", "french fries");
$result = shell_exec('python ./input.py ' . escapeshellarg(json_encode($foods)));
echo $result;
The "escapeshellarg(json_encode($foods)))" function seems to hand off my array as the following to the Python script (I get this value if I 'echo' the function:
'["pizza","french fries"]'
Then inside the Python script:
import sys, json
data = json.loads(sys.argv[1])
foods = json.dumps(data)
print(foods)
This prints out the following to the browser:
["pizza", "french fries"]
This is a plain old string, not a list. My question is, how can I best treat this data like a list, or some kind of data structure which I can iterate through with the "," as a delimiter? I don't really want to output the text to the browser, I just want to be able to break down the list into pieces and insert them into a text file on the filesystem.

Had the same problem
Let me show you what I did
PHP :
base64_encode(json_encode($bodyData))
then
json_decode(shell_exec('python ' . base64_encode(json_encode($bodyData)) );
and in Python I have
import base64
and
content = json.loads(base64.b64decode(sys.argv[1]))
as Em L already mentioned :)
It works for me
Cheers!

You can base64 foods to string, then passed to the data to Python and decode it.For example:
import sys, base64
if len(sys.argv) > 1:
data = base64.b64decode(sys.argv[1])
foods = data.split(',')
print(foods)

If you have the json string: data = '["pizza","french fries"]' and json.loads(data) isn't working (which it should), then you can use: MyPythonList = eval(data). eval takes a string and converts it to a python object

Was having problems passing json from PHP to Python, my problem was with escaping the json string, which you are doing. But looks like you were decoding then re-encoding with "food"
From what I understand
Python json.dumps(data) == PHP json_encode(data)
Python json.loads(data) == PHP json_decode(data)
json.loads(data) -> String Data
json.load(data) -> File Data
json.dumps(data) -> String Data
json.dump(data) -> File Data
PHP:
$foods = array("pizza", "french fries");
$result = shell_exec('python ./input.py ' . escapeshellarg(json_encode($foods)));
echo $result;
Python:
data = json.loads(sys.argv[1])
for v in data:
print(v)
ALSO
if you are passing key:value
PHP:
$foods = array("food1":"pizza", "food2":""french fries");
$result = shell_exec('python ./input.py ' . escapeshellarg(json_encode($foods)));
echo $result;
Python:
data = json.loads(sys.argv[1])
for(k,v) in content2.items():
print("k+" => "+v)
Python:
data = json.loads(sys.argv[1])
print(data['food1'])

Related

Does python json output values have maximum length for json_decode (php) to handle?

I am trying to write a php code that takes coefficients from a html form, sends them to a python algorithm that returns a json object. That object is a list of player names, basically {"Ji" : "Firstname Lastname"} for i from 1 to 15.
The python code (interface.py) I have to create this json is :
import json
i=0
for joueur in best_team:
i+=1
output["J%s"%(i)]=joueur['nom']
out=json.dumps(output)
print(out)
best_team is a list of player dictionnaries with data on them. My player names don't involve any non ASCII characters or whatever.
My php code is the following :
$command = "python interface.py";
$command .= " $coeff1 $coeff2 $coeff3 $coeff4 $coeff5 $coeff6 $coeff7 $coeff8 $coeff9 $coeff10 2>&1";
$pid = popen( $command,"r");
while( !feof( $pid ) )
{
$data = fread($pid, 256);
$data= json_decode($data) ;
echo $data->J1;
flush();
ob_flush();
echo "<script>window.scrollTo(0,99999);</script>";
usleep(100000);
}
pclose($pid);
I call the coefficients from the html and then send back the results via a js file.
But I just get the following error : Notice: Trying to get property of non-object.
Nothing wrong with the js file because if I try instead :
$string = '{"foo": "bar", "cool": "attributlong"}';
$result = json_decode($string);
echo $result ->cool;
It works.
Also if I have instead in my python file :
out={"foo":"bar","word":"longerthaneightcharacters"}
out=json.dumps(out)
print(out)
It works as well (replacing J1 by word in php code of course).
And funny enough, if i have in python:
output={}
i=0
for joueur in best_team:
i+=1
output["J%s"%(i)]="short"
output["J%s"%(i)]=str(output["J%s"%(i)])
out=json.dumps(output)
print(out)
It works, and if I replace "short" by "longerthaneightcharacters" it doesn't work anymore.
So basically my question is, why is there a maximum number of characters in my output loop and how can I bypass it ? Thanks, I am very confused.

Send json data to php api through python

I am new to python. I have created a gui based app to insert values into database.
I have created a Rest api to handle db operations. How can i append the api URL with json created in python.
app.py
from Tkinter import *
import tkMessageBox
import json
import requests
from urllib import urlopen
top = Tk()
L1 = Label(top, text="Title")
L1.pack( side = TOP)
E1 = Entry(top, bd =5)
E1.pack(side = TOP)
L2 = Label(top, text="Author")
L2.pack( side = TOP)
E2 = Entry(top, bd =5)
E2.pack(side = TOP)
L3 = Label(top, text="Body")
L3.pack( side = TOP)
E3 = Entry(top, bd =5)
E3.pack(side = TOP)
input = E2.get();
def callfunc():
data = {"author": E2.get(),
"body" : E3.get(),
"title" : E1.get()}
data_json = json.dumps(data)
# r = requests.get('http://localhost/spritle/api.php?action=get_uses')
#url = "http://localhost/spritle/api.php?action=insert_list&data_json="
#
url = urlopen("http://localhost/spritle/api.php?action=insert_list&data_json="%data_json).read()
tkMessageBox.showinfo("Result",data_json)
SubmitButton = Button(text="Submit", fg="White", bg="#0094FF",
font=("Grobold", 10), command = callfunc)
SubmitButton.pack()
top.mainloop()
Error:
TypeError: not all arguments converted during string formatting
i AM GETTING error while appending url with data_json ?
There is an error on string formating:
Swap this:
"http://localhost/spritle/api.php?action=insert_list&data_json="%data_json
by this:
"http://localhost/spritle/api.php?action=insert_list&data_json=" + data_json
or:
"http://localhost/spritle/api.php?action=insert_list&data_json={}".format(data_json)
The following statements are equivalents:
"Python with " + "PHP"
"Python with %s" % "PHP"
"Python with {}".format("PHP")
"Python with {lang}".format(lang="PHP")
Also, I don't think sending JSON data like this via URL is a good idea. You should encode the data at least.
You are trying to use % operator to format the string, and you need to put the %s placeholder into the string:
"http://localhost/spritle/api.php?action=insert_list&data_json=%s" % data_json
Or use other methods suggested in another answer.
Regarding the data transfer - you definitely need to use POST request and not GET.
Check this, using urllib2 and this, using requests.

sending the json data from python to php

I am sending the json data from a python program using the below code
import json
import requests
data = {"temp_value":132}
data_json = json.dumps(data)
payload = {'json_playload': data_json}
r = requests.get('http://localhost/json1/js2.php',data=payload)
and receiving it in a php server side using the below code.
<?php
if($_GET['temp_value']) {
$temp_value = $_GET['temp_value'];
echo $temp_value;
# $data = array($id, $description);
$arr=json_decode($temp_value,true);
} else {
echo "not found";}
// Connect to MySQL
include("dbconnect.php");
// Prepare the SQL statement
$SQL = "INSERT INTO test1.temperature1 (temp_value) VALUES ('$arr')";
// Execute SQL statement
mysqli_query($dbh,$SQL);
Echo "<a href=http://localhost/json1/review_data.php><center><u><b><h1>Manage values<h1><b><u></center></a>"
?>
along with the json data I have implemented like Id,time and date also gets updated in the database when i send the data.But what is happening here is like whenever i send the data from the python program it won't give any errors,when i see in the database and in the php page only 0(zero) values are inserted in both,however time and id gets updated.please someone suggest me a proper code and way.
Try this:
<?php
$json_payload = json_decode($_GET['json_payload']);
$temp_value = $json_payload['temp_value'];
?>
When you do this:
r = requests.get('http://localhost/json1/js2.php',data=payload)
You are sending a get request containing a JSON string representation of your data:
'{"temp_value": 132}'
stored in the get parameter named json_payload.
Therefore, on the client side, you must retrieve the contents of the json_payload parameter and decode the JSON string therein in order to retrieve temp_value.
Alternatively, you could do this:
payload = {"temp_value":132}
r = requests.get('http://localhost/json1/js2.php',data=payload)
And leave your PHP code unmodified.
import json
import requests
data = {"temp_value":132}
data_json = json.dumps(data)
payload = {'json_playload': data_json}
r = requests.get('http://localhost/json1/js2.php',data=payload)
print(r.url)//http://localhost/json1/js2.php
Json data is not passed in to php.Check your python code
payload = {'key1': 'value1', 'key2[]': ['value2', 'value3']}
r = requests.get("http://httpbin.org/get", params=payload)
print(r.url)
Result:
http://httpbin.org/get?key1=value1&key2%5B%5D=value2&key2%5B%5D=value3
You have to use like
payload = {"temp_value":132}

get the inverse of a php matrix from python file

PHP code:
<?php
$arr=array(array('1','2','3','4'),array('21','12','23','54'),array('10','23','35','41'),array('14','62','93','40'));
$result = shell_exec("C:/Python27/python 123.py ".json_encode($arr));
echo $result;
?>
python code:
import sys, json
arr=sys.argv[1]
print arr
A=np.matrix(arr)
print A
print ("<br/>")
M=A.I
print M
result = {'Name':'abc'}
print ("Sending data to PHP")
print (json.dumps(result))
The output given as inverse is not coming correct plus the A matrix is coming out to be of dimenesion 1x16 instead of 4x4 and the dimension of array arr is correct(4x4).How to debug it and get correct matrices A and M?
You seem not to be decoding the JSON within the Python script, whilst json_encode($arr) should be json_decode($arr) unless I'm wrong.

I have to pass an array from a php file to python file but my code is giving output NULL

PHP code:
<?php
$data = array('1','4','67','34');
$result = shell_exec('C:/Python27/python C:/xampp/htdocs/123.py ' . escapeshellarg(json_encode($data)));
$resultData = json_decode($result, true);
var_dump($resultData);
?>
Python Code:
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 = {'23','4'}
# Send it to stdout (to PHP)
print json.dumps(result)
There is incorrect data for json.dump() in Python
# Generate some data to send to PHP
result = {'23','4'}
So this give error, not json string
import sys, json
# Generate some data to send to PHP
result = {'23','4'}
# Send it to stdout (to PHP)
print json.dumps(result)
and PHP get NULL as $result from Python so you get NULL on screen - in browser
Use (for example):
# Generate some data to send to PHP
result = {'a':'23','b':'4'}
and json.dump() will work fine.
Add 2>&1 (stdout & stderr) behind the command like so:
$result = shell_exec('C:/Python27/python C:/xampp/htdocs/123.py ' . escapeshellarg(json_encode($data)) . ' 2>&1');

Categories