Skip to content

How to call Python in PHP code


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 as an extension, then modify php.ini to add


$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 ='file_get_contents', 'test.txt')

o = phpy.Object('redis')
assert'connect', '', 6379)
rdata ='uniqid')
assert'set', 'key', rdata)
assert'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

$tkinter = PyCore::import('tkinter');
$root = $tkinter->Tk();
$root->resizable(False, False);

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



Leave a message