[英]How to transfer data between Python and PHP
我有一個Python腳本,它使用print
和shell_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具有雙引號之外,這是同一件事。
如果我想使用JSON( print(json.dumps(user_vars))
,它輸出{"money": 0}
,請注意雙引號)來傳輸數據,這是我將使用的代碼:
<?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
文件中嗎? 還是我以錯誤的方式解決這個問題? 我的代碼基於此處的問題。
這段代碼可以解決問題。
import json
data = {'fruit':['oranges', 'apples', 'peaches'], 'age':12}
with open('data.json', 'w') as outfile:
json.dump(data, outfile)
<?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.