I'm storing HTML content in a MySQL field with a text data type, and I'm using ckeditor as a WYSIWYG editor to create the HTML that is being stored in MySQL. I'm looking for a way for a user to put some kind of string that I could look for and replace with calling an include file. For example:
// This string contains the text pulled from mysql
$pageContent = "<p>This page contains a calendar of events</p> {{calendar}} <p>Choose a date or scroll through days to view events.</p>";
// Function needed that changes {{calendar}} to bring in my script calendar.php like include('calendar.php');
// Note that in this example I want to call my script that does the calendar stuff, but maybe I have a script to do a photo gallery which could be {{photogallery}}, or news {{news}}, or whatever...
// Print the $pageContent including the calendar.php contents here
print $pageContent;
Here's a little something that will take your text (in this case, $pageContent
) and an array of parameters (ie array('calendar' => 'calendar.php')) and include the necessary file. It is currently untested, but should get you in the right direction.
function parseTemplate($templateText, $params)
{
foreach ($params as $key => $value)
{
ob_start();
include($value);
$includeContents = ob_get_contents();
ob_end_clean();
$templateText = str_replace('{{'.$key.'}}', $includeContents, $templateText);
}
return $templateText;
}
Usage in your case would be the following:
// This string contains the text pulled from mysql
$pageContent = "<p>This page contains a calendar of events</p> {{calendar}} <p>Choose a date or scroll through days to view events.</p>";
$params = array('calendar' => 'calendar.php');
$pageContent = parseTemplate($pageContent, $params);
// print the $pageContent including the calendar.php contents here
print $pageContent;
You could also use the same idea for simply replacing text instead of including files:
function parseTemplateText($templateText, $params)
{
foreach ($params as $key => $value)
{
$templateText = str_replace('{{'.$key.'}}', $value, $templateText);
}
return $templateText;
}