Skip to content

How to call Python in PHP code

homepage-banner

phpy is a Python and PHP interoperability library that allows you to use Python functions and libraries in PHP, or use PHP packages in Python. However, it is not language embedding. The encoding still uses their respective native syntax.

phpy enables PHP to call all Python packages, including popular libraries such as PyTorch, transformers, TensorFlow, as well as scientific computing libraries like Numpy, Pandas, Scikit, and graphical interface libraries such as PyQt, wxPython.

  • Currently, it only supports Linux platform (theoretically can support all operating systems, to be implemented)
  • Does not support Python multi-threading and async-io features

Calling Python from PHP

Compile and install phpy.so as an extension, then modify php.ini to add extension=phpy.so.

Example:

$os = PyCore::import("os");
$un = $os->uname();
echo strval($un);

Calling PHP in Python

You can directly use it as a C++ Module by importing and loading it.

import phpy

content = phpy.call('file_get_contents', 'test.txt')

o = phpy.Object('redis')
assert o.call('connect', '127.0.0.1', 6379)
rdata = phpy.call('uniqid')
assert o.call('set', 'key', rdata)
assert o.call('get', 'key') == rdata

Implementation Principle

Both ZendVM and CPython VM are created within the same process. They directly call each other using C functions within the process stack space. The only overhead is the conversion between zval and PyObject structures, making it highly efficient.

Real-life Example

Example of implementing a GUI using tkinter

<?php
$tkinter = PyCore::import('tkinter');
$root = $tkinter->Tk();
$root->title('windows');
$root->geometry("500x500");
$root->resizable(False, False);

$button = $tkinter->Button($root, text: "Click Me!!", command: PyCore::fn(function () {
    var_dump(func_get_args());
    echo 'click me!!' . PHP_EOL;
}));
$button->pack();

$tkinter->mainloop();

Reference

  • https://github.com/swoole/phpy
Leave a message