如何在Python和PHP之间传输数据 [英] How to transfer data between Python and PHP
问题描述
我有一个Python脚本,该脚本使用print
和shell_exec()
将一堆文本输出到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:
import json
# Lots of code here
user_vars = {'money':player.money}
print(user_vars)
print(json.dumps(user_vars))
输出(在PHP中):
{'money': 0} {"money": 0}
同样的事情,除了JSON带有双引号.
So the same thing, except JSON has double quotes.
如果要使用JSON(print(json.dumps(user_vars))
,输出{"money": 0}
,请注意双引号)来传输数据,这将是我要使用的代码:
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"];
?>
我有两个问题:
- 是否出于某些原因我应该使用
print(user_vars)
而不是print(json.dumps(user_vars))
,反之亦然? - 还有其他方法可以传输
user_vars
/json.dumps(user_vars)
而不在最终的PHP页面中看到它,而不必将它们转储到实际的.json
文件中吗?还是我会以错误的方式解决这个问题?
- Is there some reason I should use
print(user_vars)
instead ofprint(json.dumps(user_vars))
, or vice versa? - 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?
我的代码基于问题这里.
推荐答案
此代码可以解决问题.
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.
这篇关于如何在Python和PHP之间传输数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!