是否可以写入字符串或日志到控制台?
我的意思是
就像在JSP中一样,如果我们打印system.out.println("some")这样的东西,它将出现在控制台,而不是页面上。
是否可以写入字符串或日志到控制台?
我的意思是
就像在JSP中一样,如果我们打印system.out.println("some")这样的东西,它将出现在控制台,而不是页面上。
当前回答
作为热门答案中链接网页的作者,我想添加我最后一个版本的这个简单的助手功能。它更坚固。
我使用json_encode()来检查变量类型是否不必要,并添加一个缓冲区来解决框架的问题。header()没有稳定的返回或者使用过多。
/**
* Simple helper to debug to the console
*
* @param $data object, array, string $data
* @param $context string Optional a description.
*
* @return string
*/
function debug_to_console($data, $context = 'Debug in Console') {
// Buffering to solve problems frameworks, like header() in this and not a solid return.
ob_start();
$output = 'console.info(\'' . $context . ':\');';
$output .= 'console.log(' . json_encode($data) . ');';
$output = sprintf('<script>%s</script>', $output);
echo $output;
}
使用
// $data is the example variable, object; here an array.
$data = [ 'foo' => 'bar' ];
debug_to_console($data);`
结果截图
另外,一个简单的例子作为一个图像,更容易理解它:
其他回答
虽然这是一个老问题,但我一直在寻找这个问题。以下是我在这里回答的一些解决方案的汇编,以及在其他地方找到的一些其他想法,以获得一个通用的解决方案。
代码:
// 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中找到)而不是弹出警报。这很酷,而且可能性是无限的,你可以播放你最喜欢的音乐,让编程变得不那么有压力。
$variable = "Variable";
echo "<script>console.log('$variable');</script>";
PHP和JavaScript交互。
作为热门答案中链接网页的作者,我想添加我最后一个版本的这个简单的助手功能。它更坚固。
我使用json_encode()来检查变量类型是否不必要,并添加一个缓冲区来解决框架的问题。header()没有稳定的返回或者使用过多。
/**
* Simple helper to debug to the console
*
* @param $data object, array, string $data
* @param $context string Optional a description.
*
* @return string
*/
function debug_to_console($data, $context = 'Debug in Console') {
// Buffering to solve problems frameworks, like header() in this and not a solid return.
ob_start();
$output = 'console.info(\'' . $context . ':\');';
$output .= 'console.log(' . json_encode($data) . ');';
$output = sprintf('<script>%s</script>', $output);
echo $output;
}
使用
// $data is the example variable, object; here an array.
$data = [ 'foo' => 'bar' ];
debug_to_console($data);`
结果截图
另外,一个简单的例子作为一个图像,更容易理解它:
火狐
在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切换器
我已经放弃了上述所有工具,转而使用调试器和记录器。我怎么称赞都不为过!
只需点击右上角的一个标签,或者点击“点击这里”来展开/隐藏。
注意不同的“类别”。您可以单击任意数组展开/折叠它。
从网页
主要特点: 显示全局变量($ globals, $_POST, $_GET, $_COOKIE等) 显示PHP版本和加载的扩展 替换PHP内置的错误处理程序 记录SQL查询 监视代码和SQL查询的执行时间 检查变量的变化 函数调用跟踪 代码覆盖分析,检查执行了哪些脚本行 转储所有类型的变量 文件检查器与代码高亮显示查看源代码 发送消息到JavaScript控制台(仅限Chrome),用于Ajax脚本