I am trying to keep all the PHP files separated from the HTML files. Sort of a template based project but without using any template engines as they ar
Honestly, you should use a template system. If you don't want to hinder with learning how they work, there is a very easy approach: create a very simple one yourself. You'll need it sooner or later. The below solution should be very easy, and it's copy-pasteable.
The basic operation of such system is that you:
An example class that is very easy to comprehend might be this:
class HtmlPage
{
private $html;
# Loads specified template file into $html
public function Load($template)
{
if (!file_exists($template)) {
echo "Specified template ($template) does not exist.";
return false;
}
$this->html = file_get_contents($template);
return true;
}
# Takes in an array of data, key is the placeholder replaced, value is the new text
public function Process($data_array)
{
if (!is_array($data_array)) return;
foreach ($data_array as $search => $replace)
{
# Add brackets so they don't have to be manually typed out when calling HtmlPage::Process()
$search = "{$search}";
$this->html = str_replace($search, $replace, $this->html);
}
}
# Returns the page
public function GetHtml()
{
return $this->html;
}
}
Can be used as:
$page_title = "My fancy page title";
$page_text = "All your base are belong to us.";
$page = new HtmlPage();
$page->Load('html/templates/mypage.html');
$page->Process(array(
'TITLE' => $page_title,
'TEXT' => $page_text
));
echo $page->GetHtml();
The above code will replace
{TITLE}
{TEXT}
...to...
My fancy page title
All your base are belong to us.
In your case, this will work like the following:
html/templates/product-item.html:
PHP code:
Load('html/templates/product-list.html');
$product_html->Process(array(
'PRODUCT_NAME' => $product['name'];
'PRODUCT_ID' => $product['id'];
'PRODUCT_PRICE' => $product['price'];
'PRODUCT_PRICE_REDUCE' => $product['price_reduce'];
));
$product_list .= $product_html->GetHtml();
}
}