Reputation: 83
I am working on a project that requires a python client to execute functions and send data to a PHP server. To clarify, the python program is on a client computer, the PHP script is hosted on a webserver (24hosting). I need the python script to be able to get data from an SQL server hosted on the same site as the PHP server. I have already written code to get the SQL table data using PHP, I just need a way to get that data into python.
I am hoping the process will look like this:
Any advice on how to go about this will be greatly appreciated!
Upvotes: 1
Views: 8836
Reputation: 4884
You probably want to send the data from the PHP webserver in some easy-to-parse format such as JSON. Python has good parsing libraries for JSON, and for sending/receiving HTTP requests. The later is not part of the standard library, but can be downloaded using pip
or similar.
Upvotes: 0
Reputation: 223
You can pass data from PHP to Python via JSON like this.
PHP script myscript.php
reads a database table into a PHP array which is then encoded as JSON:
$fields = array('pkey', 'name', 'occupation');
$result = $conn->query($sql);
$row_data = array();
while ($row = $result->fetch_assoc()) {
$row_data[] = $row;
}
$rowfields = array('cols' => $fields, 'rows' => $row_data);
$json_data = json_encode($rowfields);
echo $json_data;
Then on a local computer running python:
import json
import urllib2
url = r'http://www.mysite/myscript.php'
response = urllib2.urlopen(url)
remote_data = json.load(response)
In this example, remote_data
is a python dictionary with our server data.
Upvotes: 0