将 PHP 变量存储在临时文本文件中,然后使用 python 读取该文件。
简单有效。
假设脚本在同一目录中
PHP部分
长版本(自包含脚本 - 如果您只想要代码片段,请跳到下面的短版本)
<?php
#Establish an array with all parameters you'd like to pass.
#Either fill it manually or with a loop, ie:
#Loop below creates 100 dummy variables with this pattern.
#You'd need to come up with a way yourself to fill a single array to pass
#$variable1 = '1';
#$variable2 = '2';
#$variable3 = '3';
#....
#$variableN = 'N';
#...
for ($i=1; $i<=100; $i++) {
${'variable'.$i} = $i;
}
#Create/Open a file and prepare it for writing
$tempFile = "temp.dat";
$fh = fopen($tempFile, 'w') or die("can't open file");
#let's say N=100
for ($i=1; $i<=100; $i++) {
#for custom keys
$keyname = 'Key'.$i;
# using a variable variable here to grab $variable1 ... $variable2 ... $variableN ... $variable100
$phpVariablesToPass[$keyname] = ${'variable'.$i} + 1000;
}
#phpVariablesToPass looks like this:
# [Key1] => 1001 [Key2] => 1002 [Key3] => 1003 [KeyN] = > (1000+N)
#now write to the file for each value.
#You could modify the fwrite string to whatever you'd like
foreach ($phpVariablesToPass as $key=>$value) {
fwrite($fh, $value."\n");
}
#close the file
fclose($fh);
?>
或者简而言之,假设 $phpVariablesToPass 是一个填充了您的值的数组:
#Create/Open a file and prepare it for writing
$tempFile = "temp.dat";
$fh = fopen($tempFile, 'w') or die("can't open file");
foreach ($phpVariablesToPass as $key=>$value) {
fwrite($fh, $value."\n");
}
fclose($fh);
Python Snippet 抓取数据
lines = [line.strip() for line in open('temp.dat')]
变量行现在包含所有 php 数据作为 python 列表。