I'm trying to build a system where I can create a file based in a template. The template is stored in DB and I populate the template with data sent from a form.
I've tried doing it this way but I can't get to use the array. It always gives me error.
<?php
$string = "test";
$text = "This is a text for testing";
$rplc_string = '{$string}';
$rplc_text = '{$text}';
$tpl = '<html><head><title>{$string}</title></head><body><h1>{$string}</h1><p>{$text}</p><ul><?php foreach($array as $key => $value): ?><li><?php echo $key; ?></li><?php endforeach; ?></ul></body></html>';
$tpl = preg_replace($rplc_string, $string, $tpl);
$tpl = preg_replace($rplc_text, $text, $tpl);
$array = array( 'one' => '1', 'two' => '2', 'three' => '3' );
ob_start();
eval('?>' . $tpl);
$output = ob_get_clean();
echo $output;
?>
Is there better way of doing this?
Replace out double quotes with single quotes when you are defining $tpl
also the first arg of preg_replace needs to be a regular expression:
<?php
$string = 'test';
$text = 'This is a text for testing';
$rplc_string = '/{\$string}/';
$rplc_text = '/{\$text}/';
$tpl = '<html><head><title>{$string}</title></head><body><h1>{$string}</h1><p>{$text}</p><ul><?php foreach($array as $key => $value): ?><li><?php echo $key; ?></li><?php endforeach; ?></ul></body></html>';
$array = array( 'one' => '1', 'two' => '2', 'three' => '3' );
$tpl = preg_replace($rplc_string, $string, $tpl);
$tpl = preg_replace($rplc_text, $text, $tpl);
ob_start();
eval('?>' . $tpl);
$output = ob_get_clean();
echo $output;
?>
There are several errors in your code. The first is that you believe that a variable will be interpreted between single quotes. It's false. A variable is only interpreted between double quotes or using the heredoc syntax.
The second error is a syntax error too. When you write a regex pattern you need to add delimiters. But since you have forget them, the curly brackets are seen as pattern delimiters instead of literal characters.