Is there a way to return a python variable to php?

Viewed 196

So I am making a search engine to search the internet and the engine is powered with python and the webpage for the results is in php. I need to take variables (namely, the filelist list) and return them to the php script. Please excuse any typos.

<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>

is the php code.

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))

is the python code.

1 Answers

You may write your filestoparse to a json file and then read you json file with 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
?>
Related