1. Go to this page and download the library: Download syncfly/python-in-php library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
syncfly / python-in-php example snippets
use py\json;
use py\datetime\datetime;
echo json::dumps(['hello' => 'world']); // {"hello": "world"}
echo datetime::now()->isoformat(); // 2024-01-15T12:34:56.789012
Py::eval('2 ** 10'); // 1024
Py::sum([1, 2, 3]); // 6 (Python sum(), not array_sum)
Py::sorted([3, 1, 2], reverse: true); // [3, 2, 1] — PHP named args become Python kwargs
Py::builtin('pow', 2, 8); // 256 — call any builtin by name
use py\builtins;
// with open(...) as f: — the callback receives the entered value
Py::with(builtins::open('/tmp/data.txt', 'a'), function ($f) {
$f->write(' world');
});
// the file is closed automatically when the context exits
use py\builtins;
// A PHP closure invoked by Python's map()
$doubled = builtins::list(builtins::map(fn ($x) => $x * 2, [1, 2, 3]));
// [2, 4, 6]
// As a sorting key
$sorted = builtins::sorted(['ccc', 'a', 'bb'], key: fn ($w) => strlen($w));
// ['a', 'bb', 'ccc']
use py\functools;
$adder = functools::partial(fn ($a, $b) => $a + $b, 10);
echo $adder(5); // 15 — the PHP callback runs each time Python calls the partial