Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I include a PHP script in Python?

I have a PHP script (news-generator.php) which, when I include it, grabs a bunch of news items and prints them. Right now, I'm using Python for my website (CGI). When I was using PHP, I used something like this on the "News" page:

<?php
print("<h1>News and Updates</h1>");
include("news-generator.php");
print("</body>");
?>

(I cut down the example for simplicity.)

Is there a way I could make Python execute the script (news-generator.php) and return the output which would work cross-platform? That way, I could do this:

page_html = "<h1>News and Updates</h1>"
news_script_output = php("news-generator.php") //should return a string
print page_html + news_script_output
like image 279
alecwh Avatar asked Jun 29 '09 20:06

alecwh


People also ask

How do I run a PHP script in Python?

It can be executed via the shell and the result can be returned as a string. It returns an error if NULL is passed from the command line or returns no output at all. <? php $command_exec = escapeshellcmd('path-to-.

Can we integrate PHP with Python?

You can execute python scripts using the exec() function in your php script.

Where do I put PHP scripts?

A PHP script can be placed anywhere in the document. The default file extension for PHP files is " .php ". A PHP file normally contains HTML tags, and some PHP scripting code.


2 Answers

import subprocess

def php(script_path):
    p = subprocess.Popen(['php', script_path], stdout=subprocess.PIPE)
    result = p.communicate()[0]
    return result

# YOUR CODE BELOW:
page_html = "<h1>News and Updates</h1>"
news_script_output = php("news-generator.php") 
print page_html + news_script_output
like image 135
nosklo Avatar answered Sep 30 '22 19:09

nosklo


PHP is a program. You can run any program with subprocess.

The hard part is simulating the whole CGI environment that PHP expects.

like image 43
S.Lott Avatar answered Sep 30 '22 20:09

S.Lott