"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Exchange Data and Execute Python Scripts Seamlessly from PHP?

How to Exchange Data and Execute Python Scripts Seamlessly from PHP?

Published on 2024-11-08
Browse:424

How to Exchange Data and Execute Python Scripts Seamlessly from PHP?

Executing Python Scripts and Data Exchange with PHP

It's feasible to execute Python scripts within PHP and exchange data between them. One method for doing so is through the use of common language formats and stdin/stdout for data transmission.

For example, let's consider a scenario where you have a PHP class for website data scraping. To enhance its capabilities, you're looking to integrate Python scripts designed specifically for various websites.

To facilitate data transfer between the two languages, you can leverage the following approach:

PHP:

// Data to send to Python
$data = ['as', 'df', 'gh'];

// Execute Python script with JSON data as argument
$result = shell_exec('python /path/to/myScript.py ' . escapeshellarg(json_encode($data)));

// Decode the result
$resultData = json_decode($result, true);

// This will contain: array('status' => 'Yes!')
var_dump($resultData);

Python:

import sys, json

# Load data sent from PHP
try:
    data = json.loads(sys.argv[1])
except:
    print("ERROR")
    sys.exit(1)

# Generate data to send to PHP
result = {'status': 'Yes!'}

# Send to stdout (to PHP)
print(json.dumps(result))

In this example, PHP sends JSON data as a shell argument to the Python script. The script reads the data, processes it, and sends back the result as JSON through stdout.

This method enables safe and reliable data transfer between PHP and Python. The exchange of data in structured formats like JSON ensures smooth communication and eliminates potential issues during data transfer.

Release Statement This article is reprinted at: 1729514477 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3