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

我的意思是

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


当前回答

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

代码:

    // 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中找到)而不是弹出警报。这很酷,而且可能性是无限的,你可以播放你最喜欢的音乐,让编程变得不那么有压力。

其他回答

火狐

在Firefox上,您可以使用一个名为FirePHP的扩展,它支持从PHP应用程序记录信息并将信息转储到控制台。这是一个令人敬畏的web开发扩展Firebug的插件。

http://www.studytrails.com/blog/using-firephp-in-firefox-to-debug-php/

但是如果你使用的是Chrome浏览器,有一个PHP调试工具叫做Chrome Logger或webug (webug有日志顺序的问题)。

最近,Clockwork正在积极开发中,它通过添加一个新的面板来提供有用的调试和分析信息,扩展了开发人员工具。它为Laravel 4和Slim 2提供了开箱即用的支持,并可以通过其可扩展的API添加支持。

使用Xdebug

调试PHP的更好方法是通过Xdebug。大多数浏览器都提供了辅助扩展来帮助您传递所需的cookie/查询字符串来初始化调试过程。

Chrome - Xdebug助手 Firefox -最简单的Xdebug Opera - Xdebug Safari - Xdebug切换器

试试下面的方法。它正在工作:

echo("<script>console.log('PHP: " . $data . "');</script>");

还有一个伟大的谷歌Chrome扩展,PHP控制台,有一个PHP库,可以让你:

在Chrome JavaScript控制台和弹出的通知中看到错误和异常。 转储任何类型的变量。 远程执行PHP代码。 使用密码保护访问。 根据请求对控制台日志进行分组。 跳转到文本编辑器中的错误文件:行。 将错误/调试数据复制到剪贴板(用于测试人员)。

简单的printf和json_encode:

function console_log($data) {
    printf('<script>console.log(%s);</script>', json_encode($data));
}
function phpconsole($label='var', $x) {
    ?>
    <script type="text/javascript">
        console.log('<?php echo ($label)?>');
        console.log('<?php echo json_encode($x)?>');
    </script>
    <?php
}