pass array as parameter to PHP file
I am trying to create a bunch of static HTML pages from a single PHP template. I want to pass an array (a row in a MySql DB) to the .php template file, so that I can use the contents as variables and get the HTML page back. What's the best way to do this? A POST request? A function? I loop through the MySQL query results in the following code and create an .html page for every row, but I'm not sure how to pass the $row array to the 'Template.php' file:
while ($row = mysql_fetch_array($result))
{
$variableToPass = $row;
$dynamicsource = fopen('Template.php', 'r');
$htmldata = fread($dynamicsource, 1235);
fclose($dynamicsource);
$targetfilename = "row/"
. $row['name']
. ".html";
$targetfile 开发者_StackOverflow= fopen($targetfilename, 'w');
fwrite($targetfile, $htmldata);
}
The Template.php file could look, for example, like:
<html> <body> <?php include 'mySqlTests.php'; print_r($variableToPass); ?> other text and stuff </body> </html>
So basically what you're looking to do is fetch some data from the database, then use a PHP file as a template to create a HTML file.
The easiest way to do so is to just include
the template at the appropriate point in the template generator code; you can put ob_start
and ob_get_clean
around the call to capture the output into a string instead of sending it to the client. Variables in the scope from which the include
is called will be available inside the included file. Example:
<?php
foreach ($rows as $row) {
ob_start();
include 'template.php';
$data = ob_get_clean();
file_put_contents('target/' . $row['name'] . '.html');
}
...and the template could do things like:
There are some considerations with this approach though:
- If the templates contain dangerous code, it will get executed.
- The template has access to all variabls that are in scope at the time of inclusion, including variables you don't want it to modify. This can be somewhat alleviated by putting the template call into a dedicated function.
Another approach is to do a simple search-and-replace on the loaded template; instead of using PHP as the templating language, you're basically inventing your own. This is less efficient, but safer, because you restrict the template's access to your program's internals.
Yet another option is the database to XML through XSLT route - load your data, transform it into an XML representation, apply an XSLT template that outputs (X)HTML. This has provides both flexibility and safety from injections, but XSLT is rather hard to master, harder to debug, and the conversion to XML is less efficient than the direct route to PHP.
精彩评论