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

1586010002-jmsa.png

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:

Is there some reason I should use print(user_vars) instead of

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

My code was based on the question here.

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值