我想在这里做的是从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。
当我使用opt 2运行同一个程序时,我将在python中得到这样的结果200
( ! ) 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 | ||||
---|---|---|---|---|
Call Stack | ||||
# | Time | Memory | Function | Location |
1 | 0.0000 | 240472 | {main}( ) | ..\test1.php:0 |
2 | 0.0000 | 240704 | file_get_contents ( ) | ..\test1.php:3 |
在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接收,然后将其存储在数据库中并在浏览器中显示出来。有人请给我推荐一个合适的方法来完成这个项目。