dsplos5731 2014-03-04 19:04
浏览 29
已采纳

PHP创建了一种更好的回显变量的方法

I am looking for a way to replace <?php echo $something; ?> with another notation like {$something}. But: No smarty or sth similar is used!

More detailed: At the moment, I got a .php file (with some variables inside), which includes the file "template.php". In this template file, I don't want having to use the (not very user-friendly) php notation, but replace certain strings inside this file like mentioned above. Is there any way to do so? It would be probably the best, if you could replace strings like <title></title> with <title><?php echo $title; ?></title>.

Maybe (my thoughts) I should just write the whole code into a php variable, then do some preg_replace and echo it? Or is there a more beautiful solution?

  • 写回答

2条回答 默认 最新

  • doujianjian2060 2014-03-04 19:27
    关注

    Did a similar thing several years ago wherein I had to replace several variables in an email template. What I ended up implementing was doing a str_replace on several tags. Like you, I don't want to have PHP notations or to escape characters in the template file as much as possible

    Example:

    template.php

    <html>
        <head>
            <title>[EMAIL_TITLE]</title>
        </head>
        <body>
            Hello [USER_NAME],
    
            Login here [LOGIN_LINK].
        </body>
    </html>
    

    processor.php

    $body = file_get_contents( 'template.php' );
    
    str_replace( '[EMAIL_TITLE]', $emailTitle, $body );
    str_replace( '[USER_NAME]', $userName, $body );
    str_replace( '[LOGIN_LINK]', $userName, $body );
    

    I've sinced changed implementation though to make use of PHP short tags. Using the same previous example, you could try:

    template.php

    <html>
        <head>
            <title><?= $params['title']; ?></title>
        </head>
        <body>
            Hello <?= $params['userName']; ?>!
        </body>
    </html>
    

    processor.php

    $params = array(
        'title' => $siteTitle,
        'userName' => $userName
    );
    
    ob_start();
    require_once( 'template.php' );
    $body = ob_end_clean();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改