简体   繁体   中英

condition as string inside PHP output buffer

I am using ob_start to set some content and write these contents to a file.

function get_some_contents(){
    ob_start();
    ?>
    <div class="test">
        <?php if( isset( $test ) ){
            echo 'Sample text';
        }?>
    </div>
    <?php
    return ob_get_clean();
}

I need the content in the function to write to a php file. But when i write the contents, the if condition is not written into file. Instead it is executed there itself. Is there any way other than storing it in a variable so that the if condition is added directly to buffer without executing it ?

Well, yes, you're using actual PHP tags, which will cause PHP to get interpreted. Use literally anything else to avoid that:

function get_some_contents(){
    return <<<'EOD'
        <div class="test">
            <?php if( isset( $test ) ){
                echo 'Sample text';
            }?>
        </div>
EOD;
}
function get_some_contents(){
    ob_start();
    ?>
    <div class="test">
        <?= '<?php'; ?> if( isset( $test ) ){
            echo 'Sample text';
        }?>
    </div>
    <?php
    return ob_get_clean();
}

Put this into template.php :

<div class="test">
    <?php if( isset( $test ) ){
        echo 'Sample text';
    }?>
</div>

And read it from there using file_get_contents or similar as needed.

The idea is to not use <?php and ?> tags in the code but rather stand-ins START_PHP and END_PHP , which have no meaning to PHP. But before returning the code to the caller, do the necessary text substitution replacing these pseudo-directives with the real thing:

<?php

function get_some_contents(){
    ob_start();
    ?>
    <div class="test">
        START_PHP if( isset( $test ) ){
            echo 'Sample text';
        }END_PHP
    </div>
    <?php
    $code = ob_get_clean();
    $code = str_replace('START_PHP', '<?php', $code);
    $code = str_replace('END_PHP', '?>', $code);
    return $code;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM