如果要返回的内容为空,则为默认PHP echo

时间:2015-01-19 07:20:05

标签: php header echo

让我们看看我是否可以解释自己。如果要从服务器返回的内容为空,我需要返回默认HTML模板作为回退操作。它应该是这样的:

<?php

    // Lots of code here

    // Here I could echo something
    // echo "Welcome world!";
    // but I will not so no text would be returned but ...

    // in this case I have this fallback function that will only be fired if
    // no text has been outputted by any mean before
    // fallback_template();

    fallback_template() {
        echo "<html><head><title>Empty</title></head><body>No content</body></html>";
    }

我已尝试使用headers_sent()进行检查但不起作用。有没有办法实现它还是超出了PHP的可能性?我需要 browserSync ,因此它始终保持活动状态。

1 个答案:

答案 0 :(得分:1)

    <?php
        ob_start();
        // Lots of code here

        // Here I could echo something
        // echo "Welcome world!";
        // but I will not so no text would be returned but ...

        // in this case I have this fallback function that will only be fired if
        // no text has been outputted by any mean before
        // fallback_template();

        fallback_template() {
            // buffer is empty nothing was sent to client (using print, echo or an error happened)
            if(ob_get_length() == 0 ) {            
                echo "<html><head><title>Empty</title></head><body>No content</body></html>";
            }
        }
相关问题