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

4

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

Python

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) 写入一个实际的 .json 文件中,还有其他方法可以传输这些数据,而且在最终的 PHP 页面中不会被看到吗?或者我处理这个问题的方式有误?

我的代码是基于这里的问题。


1
JSON是一种通用的格式,可以被PHP和Python以及许多其他语言解析和编写。Python的print()甚至可能无法被Python本身可靠地解析。 - Sammitch
在Python中,你会推荐使用什么命令来替代print()命令? - Tiskolin
1个回答

2
这段代码非常有用。

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

这种方法只适用于字符串,但它确实解决了我的问题,而且我可以避免使用列表/数组。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接