How do I include a PHP script in Python?

alecwh picture alecwh · Jun 29, 2009 · Viewed 7.8k times · Source

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

Answer

nosklo picture nosklo · Jun 29, 2009
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