开发者

PHP variables in HTML

Well sorry with the same question again, well i saw in phpbb there are templates in html format and they have html tags also but in between there are php array variabl开发者_高级运维es and values and in the main index file they just declared the variables and in the end the included the template and voilà! the index page is displayed without any errors now i want the same like make a variable or array and add those names in the html file like this:

index.php:

$var1 = "text";

include "file.html";

file.html:

this is {var1}

and the output should come "this is text". can anyone tell me how to do this?

EDIT: I don't want php codes like echo and all just {} and i am get output as "This is {var1}".


Thats because its using the html file as a template. I then parses through and replaces the variables with actual data.


you don't need templates.

this is <?php echo $var1?>

or if short tags are enabled

this is <?=$var1?>


I use something like this:

$content = file_get_contents($content_file);
                $pattern ='/<\$([a-zA-Z]+[a-zA-Z0-9_]*)>/';
                preg_match_all($pattern, $content, $matches);

                foreach($matches[1] as $match){
                    if(isset($$match)){
                        $content = preg_replace ('/<\$'.$match.'>/', $$match , $content, 1);
                    }

This will let you use variables like this <$varname>

If you want to use {varname} syntax just rewrite the pattern. For the $content_file be sure to include the path to the file.

Edit: Oops... had to fix my less than/greater than signs...


You can't just include file , you must read file into variable and replace {var} to $var. If you already have an array of available replacements - use str_replace to get job done. But this is bad practice , use short tags or echo instead.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜