PHP Eval that evaluates HTML & PHP

前端 未结 5 692
北海茫月
北海茫月 2020-12-06 01:22

I\'m messing around with templating and I\'ve run into a situation where I need to echo to the browser a template that contains html & php. How do I evaluate the PHP and

相关标签:
5条回答
  • 2020-12-06 02:04
    $contents = htmlentities($contents);
    echo html_entity_decode(eval($contents));
    
    0 讨论(0)
  • 2020-12-06 02:07

    In case you are trying to do this with a string of mixed HTML/PHP (like from a database, as I was), you can do it this way:

    eval(' ?>'.$htmlandphp.'<?php ');
    

    More info: http://blog.5ubliminal.com/posts/eval-for-inline-php-inside-html/ (note this is a dead link as of 2014-3-3)

    0 讨论(0)
  • 2020-12-06 02:13

    The best solution in your case is to combine eval and output buffer

    // read template into $contents
    // replace {title} etc. in $contents
    $contents = str_replace("{title}", $title, $contents);
    ob_start();
        eval(" ?>".$contents."<?php ");
    $html .= ob_get_clean();
    echo html;
    
    0 讨论(0)
  • 2020-12-06 02:14

    Do not read the file, but include it and use output bufferig to capture the outcome.

    ob_start();
    include 'main.php';
    $content = ob_get_clean();
    
    // process/modify/echo $content ...
    

    Edit

    Use a function to generate a new variable scope.

    function render($script, array $vars = array())
    {
        extract($vars);
    
        ob_start();
        include $script;
        return ob_get_clean();
    }
    
    $test = 'one';
    echo render('foo.php', array('test' => 'two'));
    echo $test; // is still 'one' ... render() has its own scope
    
    0 讨论(0)
  • 2020-12-06 02:24

    Use output buffering instead. eval() is notoriously slow.

    main.php:

    <div id="container">
        <div id="title"><?php echo $title; ?></div><!-- you must use PHP tags so the buffer knows to parse it as such -->
        <div id="head">
            <?php if ($id > 10): ?>
                <H3>Greater than 10!</H3>
            <?php else: ?>
                <H3>Less than 10!</H3>
            <?php endif ?>
        </div>
    </div>
    

    Your file:

    $title = 'Lorem Ipsum';
    $id = 11;
    
    ob_start();
    require_once('main.php');
    $contents = ob_get_contents();
    ob_end_clean();
    
    echo $contents;
    

    The output of this will be:

    Lorem Ipsum

    Greater than 10!

    0 讨论(0)
提交回复
热议问题