Domanda

I have an internal server that is generating JSON every few minutes. I need to pass this to and external server so I can manipulate the data and then present it in web interface. Here is my python that send the data to PHP script:

x = json.dumps(data)

print '\nHTTP Response'

headers = {"Content-type": "application/json"}

conn = httplib.HTTPConnection("myurl.com")

conn.request("POST", "/recieve/recieve.php", x, headers)
response = conn.getresponse()
text = response.read()
print "Response status: ",response.status,"\n",text
conn.close()

and Here is my PHP to receive the data

$data = file_get_contents('php://input');
$objJson = json_decode($data);
print_r ($objJson);

My python script return with response status 200 which is good and it returns my JSON. But on the PHP side I want to be able to store this information to manipulate and then have a web client grab at it. However it appears that even if I say

print_r ($objJson);

when I visit the .php page it does not print out my object. I suppose the data is gone because file::input will read only and then end?

È stato utile?

Soluzione

Don't use file_get_contents()

Just:

if($_POST){ echo "WE got the data"; }

and print_r will help you with where to go from there, if you are unfamiliar with PHP arrays.

Altri suggerimenti

Try to use named parameter containing your JSON data while sending data to PHP and try to use the $_POST superglobal array in PHP (because you obviously connecting via cgi or similar interface not via cli). You can see all the POST data by printing your $_POST array:

print_r($_POST);

Here is what I did in the end as a quick fix

the python

x = json.dumps(data)
headers = {"Content-type": "application/json"}
conn = httplib.HTTPConnection("myurl.com")

conn.request("POST", "/script.php", x, headers)
response = conn.getresponse()
text = response.read()
print "Response status: ",response.status,"\n",text
conn.close()   

then I realized that the PHP was receiving the post data but I was having a hard time manipulating it. So I just sent the JSON to a receiving PHP file that wrote the data as file and then has another JavaScript request grab that. the php

if($_POST){ echo "WE got the data\n"; } //thanks rm-vanda
$data = file_get_contents('php://input');
$file = 'new.json';
$handle = fopen($file, 'a');
fwrite($handle, $data);
fclose($handle);
exit;

Then from my client just a ajax request for the file and parsed it on the client side.

Eventually I have to rethink this but it works for now. I also have to rewrite over the new.json file each time new data comes in or parse the old data out on the JavaScript success callback. Depends what you want to do.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top