使用者:游士賢
出自福留子孫
php呼叫python顯示於網頁
範例一、文字顯示
- 說明:利用 php 讀取 python 檔案,並將文字顯示於頁面上。
- 範例程式:連結
test.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>PHP呼叫Python範例</title>
</head>
<body>
<?php
$output = shell_exec('python word.py'); // 用 shell_exec 函式呼叫 Python 程式並取得輸出
echo "<pre>$output</ pre>"; // 將輸出作為純文本輸出到 HTML 頁面上
?>
</body>
</html>
word.py
print("Hello, world!")
範例二、兩數相加算術
index.php
<!DOCTYPE html>
<html>
<head>
<title>兩數相加算術範例</title>
</head>
<body>
<h2>兩數相加算術</h2>
<form method="POST">
<label>請輸入第一個數字:</label>
<input type="text" name="num1">
<br><br>
<label>請輸入第二個數字:</label>
<input type="text" name="num2">
<br><br>
<input type="submit" name="submit" value="計算">
</form>
<?php
if(isset($_POST['submit'])){
$num1 = $_POST['num1'];
$num2 = $_POST['num2'];
$python_path = "/usr/bin/python"; // 設定 Python 可執行文件的路徑
$python_script = "calculate.py"; // 要執行的 Python 腳本路徑
// 執行 Python 腳本,並傳遞數字參數
$command = escapeshellcmd("$python_path $python_script $num1 $num2");
$output = shell_exec($command);
echo "<p>答案:$output</p>"; // 在網頁上顯示 Python 腳本的輸出
}
?>
</body>
</html>
calculate.py
import sys # 獲取從 PHP 傳遞的兩個數字參數 num1 = float(sys.argv[1]) num2 = float(sys.argv[2]) # 執行算術操作 result = num1 + num2 # 將結果返回給 PHP print(result)