将json数据从python发送到php

时间:2015-02-28 05:15:59

标签: 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方面得到200 POST Variable not found,在php方面得到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 个答案:

答案 0 :(得分:0)

选项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 Web服务器,并在其根目录下创建一个名为 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>