是否可以写入字符串或日志到控制台?

我的意思是

就像在JSP中一样,如果我们打印system.out.println("some")这样的东西,它将出现在控制台,而不是页面上。


当前回答

$variable = "Variable";
echo "<script>console.log('$variable');</script>";

PHP和JavaScript交互。

其他回答

虽然这是一个老问题,但我一直在寻找这个问题。以下是我在这里回答的一些解决方案的汇编,以及在其他地方找到的一些其他想法,以获得一个通用的解决方案。

代码:

    // Post to browser console
    function console($data, $is_error = false, $file = false, $ln = false) {
        if(!function_exists('console_wer')) {
            function console_wer($data, $is_error = false, $bctr, $file, $ln) {
                echo '<div display="none">'.'<script type="text/javascript">'.(($is_error!==false) ? 'if(typeof phperr_to_cns === \'undefined\') { var phperr_to_cns = 1; document.addEventListener("DOMContentLoaded", function() { setTimeout(function(){ alert("Alert. see console."); }, 4000); });  }' : '').' console.group("PHP '.(($is_error) ? 'error' : 'log').' from "+window.atob("'.base64_encode((($file===false) ? $bctr['file'] : $file)).'")'.((($ln!==false && $file!==false) || $bctr!==false) ? '+" on line '.(($ln===false) ? $bctr['line'] : $ln).' :"' : '+" :"').'); console.'.(($is_error) ? 'error' : 'log').'('.((is_array($data)) ? 'JSON.parse(window.atob("'.base64_encode(json_encode($data)).'"))' : '"'.$data.'"').'); console.groupEnd();</script></div>'; return true;
            }
        }
        return @console_wer($data, $is_error, (($file===false && $ln===false) ? array_shift(debug_backtrace()) : false), $file, $ln);
    }
    
    //PHP Exceptions handler
    function exceptions_to_console($svr, $str, $file, $ln) {
        if(!function_exists('severity_tag')) {
            function severity_tag($svr) {
                $names = [];
                $consts = array_flip(array_slice(get_defined_constants(true)['Core'], 0, 15, true));
                foreach ($consts as $code => $name) {
                    if ($svr & $code) $names []= $name;
                }
                return join(' | ', $names);
            }
        }
        if (error_reporting() == 0) {
            return false;
        }
        if(error_reporting() & $svr) {
            console(severity_tag($svr).' : '.$str, true, $file, $ln);
        }
    }

    // Divert php error traffic
    error_reporting(E_ALL);  
    ini_set("display_errors", "1");
    set_error_handler('exceptions_to_console');

测试和使用:

使用方法很简单。包括手动发布到控制台的第一个函数。使用第二个函数转移php异常处理。下面的测试应该可以给出一个想法。

    // Test 1 - Auto - Handle php error and report error with severity info
    $a[1] = 'jfksjfks';
    try {
          $b = $a[0];
    } catch (Exception $e) {
          echo "jsdlkjflsjfkjl";
    }

    // Test 2 - Manual - Without explicitly providing file name and line no.
          console(array(1 => "Hi", array("hellow")), false);
    
    // Test 3 - Manual - Explicitly providing file name and line no.
          console(array(1 => "Error", array($some_result)), true, 'my file', 2);
    
    // Test 4 - Manual - Explicitly providing file name only.
          console(array(1 => "Error", array($some_result)), true, 'my file');
    

解释:

The function console($data, $is_error, $file, $fn) takes string or array as first argument and posts it on console using js inserts. Second argument is a flag to differentiate normal logs against errors. For errors, we're adding event listeners to inform us through alerts if any errors were thrown, also highlighting in console. This flag is defaulted to false. Third and fourth arguments are explicit declarations of file and line numbers, which is optional. If absent, they're defaulted to using the predefined php function debug_backtrace() to fetch them for us. Next function exceptions_to_console($svr, $str, $file, $ln) has four arguments in the order called by php default exception handler. Here, the first argument is severity, which we further crosscheck with predefined constants using function severity_tag($code) to provide more info on error.

注意:

以上代码使用的JS函数和方法在旧浏览器中是不可用的。为了与旧版本兼容,它需要替换。 上面的代码是用于测试环境的,在测试环境中只有您可以访问站点。不要在实际(生产)网站中使用。

建议:

第一个函数console()抛出了一些通知,所以我将它们包装在另一个函数中,并使用错误控制操作符“@”调用它。如果你不介意这些提示,这是可以避免的。 最后但并非最不重要的是,在编码时弹出警报可能会令人讨厌。为此,我使用这个哔哔声(在解决方案:https://stackoverflow.com/a/23395136/6060602中找到)而不是弹出警报。这很酷,而且可能性是无限的,你可以播放你最喜欢的音乐,让编程变得不那么有压力。

我认为最好的解决办法是使用 error_log(内容) 这是输出

2022年编辑:

所以我发现了更好的方法,那就是file_put_contents("php://stdout",内容)

它在没有日志信息的情况下进行写入

默认情况下,所有输出都输出到stdout,即HTTP响应或控制台,这取决于脚本是由Apache运行还是在命令行上手动运行。但是您可以使用error_log进行日志记录,并且可以使用fwrite写入各种I/O流。

我已经放弃了上述所有工具,转而使用调试器和记录器。我怎么称赞都不为过!

只需点击右上角的一个标签,或者点击“点击这里”来展开/隐藏。

注意不同的“类别”。您可以单击任意数组展开/折叠它。

从网页

主要特点: 显示全局变量($ globals, $_POST, $_GET, $_COOKIE等) 显示PHP版本和加载的扩展 替换PHP内置的错误处理程序 记录SQL查询 监视代码和SQL查询的执行时间 检查变量的变化 函数调用跟踪 代码覆盖分析,检查执行了哪些脚本行 转储所有类型的变量 文件检查器与代码高亮显示查看源代码 发送消息到JavaScript控制台(仅限Chrome),用于Ajax脚本

echo 
"<div display='none'>
    <script type='text/javascript'>
        console.log('console log message');
    </script>
</div>";

创建一个

<div>

display="none"

这样就不会显示div,而是

console.log()

函数是用javascript创建的。因此,您在控制台中获得消息。