Running Python Scripts and Exchanging Data in PHP
One can integrate Python scripts into PHP applications for more specific data extraction from websites. Here's how:
Communication via Common Format and Standard Pipes:
To facilitate data transfer, utilize shared formats like JSON. PHP and Python communicate through stdin (for input) and stdout (for output).
Python Script Execution with PHP:
Pass data to the Python script as a JSON string via a shell argument in PHP:
<code class="php">$data = array('as', 'df', 'gh'); $result = shell_exec('python /path/to/myScript.py ' . escapeshellarg(json_encode($data)));</code>
Decoding Python's Response in PHP:
Access the Python script's output, decode the JSON response, and store it in a PHP variable:
<code class="php">$resultData = json_decode($result, true);</code>
Python Script Implementation:
<code class="python">import sys, json # Load data from PHP data = json.loads(sys.argv[1]) # Generate response data result = {'status': 'Yes!'} # Output response to PHP via stdout print json.dumps(result)</code>
In summary, you can execute Python scripts within PHP, exchange data via JSON serialization, and utilize stdin/stdout for communication, enabling seamless data transfer between the two languages.
The above is the detailed content of How to Integrate Python Scripts into PHP Applications and Exchange Data?. For more information, please follow other related articles on the PHP Chinese website!