php - 将json数据从python发送到php

标签 php python json

我想在这里做的是从 python 程序发送 json 数据并在 php 中接收并将其存储在数据库中并在浏览器中显示。

这是我用于从 python 发送 json 数据的代码:

import httplib,json,urllib
headers = { "charset":"utf-8",
"Accept": "text/plain"}
conn = httplib.HTTPConnection("localhost")
#converting list to a json stream
bulkData={"temp_value":123}
bulkData = json.dumps(bulkData, ensure_ascii = 'False')
# ensure_ascii is false as data is in unicode and not ascii encoding , use this if data is in any other encoding
postData = urllib.urlencode({'results':bulkData})
conn.request("POST", "/test1.php", postData,headers)
response = conn.getresponse()
text = response.read()
print response.status,text
conn.close()

这些是我用来从 python 接收 json 数据的 php 代码: 选择 1)

<?php
if (isset($_POST['results']))
{
$data = json_decode($_POST['results']);
// This is to decode the json stream, using a function called json_decode()
foreach($data as $record) // ACCESS each record individually
{
foreach($record as $key => $value)
{
echo $key . '->' .$value;
// you can get individual key , value pairs (if content is in dictionary format)
}
}
}
else
{
    echo $data;
echo 'POST Variable not found';
}
?>

选择 2)

<?php
$url = "http://localhost/pyjson.py";
$json = file_get_contents($url);
$json_data = json_decode($json, true);
echo "temp value: ". $json_data["temp_value"];
?>

当我使用选项 1 运行 python 时,我在 python 端和 php 端得到类似 200 POST Variable not found 的消息,我得到类似 POST Variable not found 的消息。

当我使用 opt 2 运行相同的程序时,我将在 python 中得到这样的结果

200 <br />
<font size='1'><table class='xdebug-error xe-warning' dir='ltr' border='1' cellspacing='0' cellpadding='1'>
<tr><th align='left' bgcolor='#f57900' colspan="5"><span style='background-color: #cc0000; color: #fce94f; font-size: x-large;'>( ! )</span> Warning: file_get_contents(http://localhost/pyjson.py): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found

 in C:\wamp\www\test1.php on line <i>3</i></th></tr>
<tr><th align='left' bgcolor='#e9b96e' colspan='5'>Call Stack</th></tr>
<tr><th align='center' bgcolor='#eeeeec'>#</th><th align='left' bgcolor='#eeeeec'>Time</th><th align='left' bgcolor='#eeeeec'>Memory</th><th align='left' bgcolor='#eeeeec'>Function</th><th align='left' bgcolor='#eeeeec'>Location</th></tr>
<tr><td bgcolor='#eeeeec' align='center'>1</td><td bgcolor='#eeeeec' align='center'>0.0000</td><td bgcolor='#eeeeec' align='right'>240472</td><td bgcolor='#eeeeec'>{main}(  )</td><td title='C:\wamp\www\test1.php' bgcolor='#eeeeec'>..\test1.php<b>:</b>0</td></tr>
<tr><td bgcolor='#eeeeec' align='center'>2</td><td bgcolor='#eeeeec' align='center'>0.0000</td><td bgcolor='#eeeeec' align='right'>240704</td><td bgcolor='#eeeeec'><a href='http://www.php.net/function.file-get-contents' target='_new'>file_get_contents</a>
(  )</td><td title='C:\wamp\www\test1.php' bgcolor='#eeeeec'>..\test1.php<b>:</b>3</td></tr>
</table></font>

在 php 方面我得到了

Warning: file_get_contents(http://localhost/pyjson.py): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found in C:\wamp\www\test1.php on line 3

我想在这里做的是从 python 程序发送 json 数据并在 php 中接收并将其存储在数据库中并在浏览器中显示。请有人建议我一个正确的方法来完成这个程序。

最佳答案

选项 1 非常接近,但看起来您正在尝试对您从 Python 创建的 POST 请求进行 URL 编码,然后将其解码为 JSON,不幸的是,这不起作用。您要做的是将 JSON 本身作为 POST 请求的主体发送,然后在您的 PHP 服务器上使用它。

创建一个名为 provider.py 的文件并使用它的内容:

import httplib, json
headers = { "charset" : "utf-8", "Content-Type": "application/json" }

conn = httplib.HTTPConnection("localhost")

sample = { "temp_value" : 123 }

sampleJson = json.dumps(sample, ensure_ascii = 'False')

# Send the JSON data as-is -- we don't need to URL Encode this
conn.request("POST", "/consumer.php", sampleJson, headers)

response = conn.getresponse()

print(response.read())

conn.close()

然后,设置一个 PHP 网络服务器,并在其根目录下创建一个名为 consumer.php 的文件,内容如下:

<?

// Function to print out objects / arrays
function PrintObj ($o) { echo "<pre>"; print_r($o); echo "</pre>"; }

// Load the POST.
$data = file_get_contents("php://input");

// ...and decode it into a PHP array.
$data = json_decode($data); 

// Do whatever with the array. 
PrintObj($data);

从这里,如果你跑

$ python provider.py

您应该将以下输出输出到控制台:

<pre>stdClass Object
    (
        [temp_value] => 123
    )
</pre>

关于php - 将json数据从python发送到php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28778384/

相关文章:

php - 如何有效地从大表中计算平均值?

python - 我可以将 prettytable 创建的输出格式写入文件吗?

python - 在 Python 中打开 Alteryx .yxdb 文件?

python - 将 JSON 对象解析为 Django 模板

ruby - 将 JSON 提要消费到适当的 Ruby 中

javascript - AJAX成功回调

php - 在触发事件时将 php 变量插入数据库

php - 将编辑文本值从 android 插入到 mysql

php - 在 PHP 中删除选定的记录

python - 如何将特殊字符 ("\n","\b",...) 写入 Python 文件?