How to output static web pages from PHP on command line – convert a PHP page to its HTML output on the command line. This article shows how to output HTML from PHP in a terminal.
The objective of this article is to show how to output an HTML web page from an input PHP script without using a web browser. Instead the output HTML page is generated on the command line in a terminal window.
Using PHP in this way allows it to be used in a template system to generate static HTML from PHP. PHP can handle common parts of a web site such as the header, footer and menu, but is not required to run on the web server. Only the output HTML will need to be hosted on the web server.
How to Output HTML from PHP
Two steps are required to generate static HTML page output from a PHP page input on the command line, namely, first install php-cgi and then invoke it from the command line to generate the page.
Using just php on the command line will not work, as it strips out all of the HTML tags, leaving plain text content as its output. It is necessary to install php-cgi as follows (example for a Debian based system such as Linux Mint or Ubuntu using apt):
sudo apt install php-cgi
Run php-cgi from the Command Line
To get an HTML output file from a PHP input file, use php-cgi in a terminal window using the following format:
php-cgi -q <input php file> > <output html file>
For example, with an input file called phpinfo.php with the following content:
Enter the following on the command line:
php-cgi -q phpinfo.php > phpinfo.html
This produces an output HTML file called phpinfo.html that contains HTML generated from the input phpinfo.php file.
More About php-cgi
The -q switch used above stops HTTP header output from being placed at the top of the output HTML file which looks as follows if not used.
Content-type: text/html; charset=UTF-8
Other switches for php-cgi are as follows.
Usage: php [-q] [-h] [-s] [-v] [-i] [-f <file>] php <file> [args…] -a Run interactively -b <address:port>|<port> Bind Path for external FASTCGI Server mode -C Do not chdir to the script's directory -c <path>|<file> Look for php.ini file in this directory -n No php.ini file will be used -d foo[=bar] Define INI entry foo with value 'bar' -e Generate extended information for debugger/profiler -f <file> Parse <file>. Implies `-q' -h This help -i PHP information -l Syntax check only (lint) -m Show compiled in modules -q Quiet-mode. Suppress HTTP Header output. -s Display colour syntax highlighted source. -v Version number -w Display source with stripped comments and whitespace. -z <file> Load Zend extension <file>. -T <count> Measure execution time of script repeated <count> times.