Home >Backend Development >PHP Tutorial >Data interaction between PHP and Python

Data interaction between PHP and Python

藏色散人
藏色散人forward
2019-10-26 14:18:074529browse

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
<?php
$params = "value"; #传递给python脚本的入口参数  
$path="python python.py "; //需要注意的是:末尾要加一个空格
passthru($path.$params);//等同于命令`python python.py 参数`,并接收打印出来的信息 
?>

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 = (&#39;Google&#39;, &#39;Runoob&#39;, 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 visit PHP 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!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete