Есть ли способ вернуть переменную python в php? - PullRequest
2 голосов
/ 02 августа 2020

Итак, я делаю поисковую машину для поиска по inte rnet, и эта машина работает с python, а веб-страница для результатов находится в php. Мне нужно взять переменные (а именно список filelist) и вернуть их в сценарий php. Извините за возможные опечатки.

<html>
    <head>
        <script src='searchengine.js' type='text/javascript'></script>
    </head>
    <body>
        <?php
        $cmd='python3 searchresult.py'+$_POST["searchquery"];
        $output = shell_exec($cmd);
        echo $output;
        ?>
        
    </body>
 </html>

- это код php.

import sys
from os import listdir, basename
import re

keyword=sys.argv[1]
keyword=str(keyword)
filelist=[]
db='C:\\Users\\monik\\Documents\\searchengine\\db'
filestoparse=listdir(db)
for file in filestoparse:
    with open(file,  'r') as f:
        filecontent=str(f.read)
        result=re.findall(keyword, filecontent)
        if len(result)>=5:
            filelist.append(basename(f.name))

- это код python.

1 Ответ

0 голосов
/ 02 августа 2020

Вы можете записать свой filestoparse в json файл, а затем прочитать ваш json файл с php.

Python

import json 
#parse files in directory to dictionary 
filestoparsetodict ={'file1':'myfile.cdr', 'file2':'picture.psd'}

# write your dictionary to json file
out_file = open("C:/xampp/htdocs/phpjson/myfile.json", "w") 
json.dump(filestoparsetodict, out_file) 
out_file.close()

PHP

<?php
$filelist = file_get_contents("myfile.json");
// Convert content to array 
$myarray = json_decode($filelist, true);
echo $myarray["file1"]; // print an item from array objects
?>
...