繁体   English   中英

如何在Python和PHP之间传输数据

[英]How to transfer data between Python and PHP

我有一个Python脚本,它使用printshell_exec()将一堆文本输出到PHP。 我还必须在两者之间发送字典,以存储一些脚本信息。 这是我的代码的简化版本:

蟒蛇

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具有双引号之外,这是同一件事。

PHP

如果我想使用JSON( print(json.dumps(user_vars)) ,它输出{"money": 0} ,请注意双引号)来传输数据,这是我将使用的代码:

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

我有两个问题:

  1. 有什么原因我应该使用print(user_vars)而不是print(json.dumps(user_vars)) ,反之亦然?
  2. 还有其他方法可以传输user_vars / json.dumps(user_vars)而不必在最终的PHP页面中看到它,而不必将其转储到实际的.json文件中吗? 还是我以错误的方式解决这个问题?

我的代码基于此处的问题。

这段代码可以解决问题。

蟒蛇

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
?>

该方法仅适用于字符串,但确实解决了我的问题,我可以不使用列表/数组来解决问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM