Hacks: Python Calling PHP

(This is almost too stupid to post, but on the off chance that someone actually needs something like this…)

I needed to interface with a bunch of data that had PHP wrapper classes, and needed a quick way of being able to interface with PHP from Python. (At this point, you might find it hard to believe that the PHP wrapper classes were worth trying to reuse, but the wrapper classes took care of partitioning and caching and everything, so it seemed silly to not reuse them). I considered using the PHP API and ctypes to make a Python to PHP bridge , but then decided that was entirely too much work, so I just hacked together a stupid class that invoked PHP with arbitrary code and returned it in a number of ways.

Basic usage

Create the PHP class (giving it an optional prefix and postfix — prefix is the most useful, as it allows you to specify requires), and then invoke a code block with get_raw, get, or get_one. Note that every “call” into PHP will create and destroy a PHP process.

Some examples:

Reading raw input

php = PHP("require '../code/private/common.php';")
code = """for ($i = 1; $i <= 10; $i++) { echo "$i\n"; }"""
print php.get_raw(code)

will output a string containing the numbers “1″..”10″

Reading one big JSON value

php = PHP("require '../code/private/common.php';")
code = """                                                                                          
$a = array();                                                                                       
for ($i = 1; $i <= 10; $i++) { $a[] = $i; }                                                         
echo json_encode($a);"""
print php.get(code)

This code would return a Python list with the numbers 1..10.

Reading many JSON values

    php = PHP("require '../code/private/common.php';")
    code = """                                                                                          
    for ($i = 1; $i <= 10; $i++) {                                                                      
        echo json_encode(array($i => $i * $i)) . "\n";                                                  
    }"""
    for row in php.get_one(code):
        print row

Given a PHP snippet that returns one JSON value per line, iterate through them as Python values.

Find it on Github.

3 thoughts on “Hacks: Python Calling PHP

  1. Drucik

    Hi!
    As you wrote, someone may needs something like this.
    For me it worked (only warning about popen2 being obsolete) and was very helpful :)

    Reply
  2. Pingback: Co obnáší registrace domén skriptem

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" cssfile="">