Home>Article>Backend Development> Data interaction between PHP and Python
Recently, I decided to use tp5 for APP interface development and Python for data analysis in a project. Then I faced a question: How do PHP and Python interact with data?
Ideas
The way I solved this problem was to use PHP's passthru function to call the command to run the Python script.
Implementation
Call the command in PHP to run the Python script
//php.php
If there are multiple parameters, separate them with spaces
Receive the parameters passed in by PHP in Python
sys.argv[] is used to obtain the entry parameters passed by PHP into python
//python.py import sys params = sys.argv[1] #即为获取到的PHP传入python的入口参数 print(params);
If in Receive multiple parameters in Python
params = sys.argv[1:]
Return parameters from Python
To return multiple values from Python, you need to write the values into a tuple, and then Convert it to json through json.dumps() and print it. You can get the json printed by the Python script through passthru in PHP
import sys import json params = ('Google', 'Runoob', 1997, 2000); json_str =json.dumps(params); print(json_str);
You also need to add @ before passthru in PHP, otherwise the following prompt will be reported
Notice: Array to string conversion in php.php on line 6
Effect
Run the PHP file that calls the Python script, and the output value in the browser is the value printed by Python.
For more PHP related knowledge, please visitPHP Chinese website!
The above is the detailed content of Data interaction between PHP and Python. For more information, please follow other related articles on the PHP Chinese website!