Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

read output of php file using python

I have a php file on server that prints some data from the mysql database in json format.

When I run my php file in my browser I can see the json array. Now I want to get that json array in a python file. Is there a way to do it?

here is the code i am using

import subprocess
import json
import codecs

proc = subprocess.Popen("http://www.rpi-connect.esy.es/getappliances?room=1", shell=True, stdout=subprocess.PIPE)
script_response = str(proc.stdout.read().decode('utf8'))
print(script_response)
like image 886
M2skills Avatar asked May 12 '26 05:05

M2skills


1 Answers

I finally got the answer after trying a lot of different python libraries

import json
import urllib.request
url = "http://example.com/your-filename.php"
x = urllib.request.urlopen(url)
raw_data = x.read()
encoding = x.info().get_content_charset('utf8')  # JSON default
print(raw_data)   #this is data in string format
data = json.loads(raw_data.decode(encoding))
print(data)   #this would be your json data

this works for python 3.4. for python 2.7 try using json.load() instead of json.loads()

like image 94
M2skills Avatar answered May 14 '26 19:05

M2skills