Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to transfer data between Python and PHP

I have a Python script that outputs a bunch of text to PHP using print and shell_exec(). I also have to send a dictionary between the two, to store some script information. Here is a simplified version of my code:

Python

import json

# Lots of code here

user_vars = {'money':player.money}
print(user_vars)
print(json.dumps(user_vars))

which outputs (in PHP):

{'money': 0} {"money": 0}

So the same thing, except JSON has double quotes.

PHP

This is the code I would use if I wanted to use JSON (print(json.dumps(user_vars)), which outputs {"money": 0}, note double quotes) to transfer data:

<?php
$result = shell_exec('python JSONtest.py');
$resultData = json_decode($result, true);
echo $resultData["money"];
?>

I have two questions:

  1. Is there some reason I should use print(user_vars) instead of print(json.dumps(user_vars)), or vice versa?
  2. Is there some other way to transfer user_vars/json.dumps(user_vars) without it being seen in the final PHP page without having to dump them in an actual .json file? Or am I going about this problem in the wrong way?

My code was based on the question here.

like image 236
Tiskolin Avatar asked Oct 19 '25 10:10

Tiskolin


1 Answers

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.

like image 103
Tiskolin Avatar answered Oct 22 '25 01:10

Tiskolin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!