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


Default PHP echo if the content to return is empty

让我们看看我是否可以解释一下自己。如果要从服务器返回的内容为空,我需要返回默认 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的可能性?我需要它进行浏览器同步,因此它始终保持活动状态。

    <?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>";
            }
        }