06 Oct 2005

Python simple data exchange with PHP

Filed under: Development | Taged as: , | 0 comments

Python is a very powerful language and its features and syntax allow some tasks to be done in a more ellegant manner then with PHP (think about shell programms for example). So it might be a good thing to get a kind of integration or direct exchange with PHP (which also has its benefits, now doubt). The use of web services might be a good idea, but they would be an overkill in (smaller) applications.

The execution of python scripts via PHP is no problem (via HTTP and streams or via system()) but the data exchange in between needs a closer look. PHP has a native serialize method which even allows to turn objects and arrays into a string representation. Python on the other side does not come up with an equivalent version. But doing the (un)serialization “by hand” enables a perfect and simple interchange of structured data.

The PHPSerializer class itself turns the input types into their corresponding string representation based on an very simple mapping:

"""
type mapping:
python         php               serialized
none    <=>    NULL        =>    N;
bool    <=>    bool        =>    b:1;|b:0;
long    <=>    double      =>    d:$data;
int     <=>    int         =>    i:$data;
float   <=>    double      =>    d:$data;
string  <=>    string      =>    s:$length:$data;
tuples  <=>    array
list    <=>    array
dict    <=>    array       =>    a:$count:{(i|s):$key;(i|s|a):value};
"""

The usage of the class is then very intuitive:

#!/usr/bin/python
print "Content-type: text/html"
print

import cgitb
import cgi
import sys

from PHPSerializer import *

data = cgi.FieldStorage()["data"].value

try:
tmp = PHPSerializer.unserialize(data)
tmp['a'] = "hello python"
tmp['b'] = [5,6,7,8]
tmp['c']['orange'] = ["a", "b", "c", "d"]
print PHPSerializer.serialize(tmp)

except Exception, e:
print e

In the example, an array is serialized and send to an python script via an HTTP stream. The script unserializes the data, manipulates it and return the re-serialized array back to PHP.

Check out the Python / PHP serializer project page or download the

Related posts

Share and Enjoy:

  • RSS
  • Digg
  • del.icio.us
  • Google Bookmarks
  • FriendFeed
  • MisterWong
  • StumbleUpon
  • Technorati
  • Twitter
  • NewsVine

Leave a Reply