[英]How can I write to the console in PHP?
是否可以写入字符串或登录控制台?
就像在 JSP 中一样,如果我们打印类似system.out.println("some")
,它将出现在控制台上,而不是在页面上。
或者您使用从PHP Debug 到 console的技巧。
首先你需要一个小的 PHP 辅助函数
function debug_to_console($data) {
$output = $data;
if (is_array($output))
$output = implode(',', $output);
echo "<script>console.log('Debug Objects: " . $output . "' );</script>";
}
然后你可以像这样使用它:
debug_to_console("Test");
这将创建如下输出:
Debug Objects: Test
火狐
在 Firefox 上,您可以使用名为FirePHP的扩展程序,它可以将信息从 PHP 应用程序记录和转储到控制台。 这是令人敬畏的 Web 开发扩展Firebug的插件。
铬合金
但是,如果您使用的是 Chrome,则有一个名为Chrome Logger或webug的 PHP 调试工具(webug 有日志顺序问题)。
最近, Clockwork正在积极开发中,它通过添加一个新面板来扩展开发人员工具,以提供有用的调试和分析信息。 它为Laravel 4和Slim 2提供开箱即用的支持,并且可以通过其可扩展的 API 添加支持。
使用 Xdebug
调试 PHP 的更好方法是通过Xdebug 。 大多数浏览器都提供辅助扩展来帮助您传递所需的 cookie/查询字符串来初始化调试过程。
如果您正在寻找一种简单的方法,请作为 JSON 回显:
<script>
console.log(<?= json_encode($foo); ?>);
</script>
请尝试以下操作。 这是工作:
echo("<script>console.log('PHP: " . $data . "');</script>");
作为热门答案中链接网页的作者,我想添加这个简单帮助函数的最新版本。 它要坚固得多。
我使用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);`
另外,一个简单的例子作为图像更容易理解:
echo
"<div display='none'>
<script type='text/javascript'>
console.log('console log message');
</script>
</div>";
创建一个
<div>
与
display="none"
以便不显示 div,但
console.log()
函数是在javascript中创建的。 所以你会在控制台中收到消息。
$variable = "Variable";
echo "<script>console.log('$variable');</script>";
PHP 和 JavaScript 交互。
我觉得可以用——
function jsLogs($data) {
$html = "";
$coll;
if (is_array($data) || is_object($data)) {
$coll = json_encode($data);
} else {
$coll = $data;
}
$html = "<script>console.log('PHP: ${coll}');</script>";
echo($html);
# exit();
}
# For String
jsLogs("testing string"); #PHP: testing string
# For Array
jsLogs(array("test1", "test2")); # PHP: ["test1","test2"]
# For Object
jsLogs(array("test1"=>array("subtest1", "subtest2"))); #PHP: {"test1":["subtest1","subtest2"]}
一些很好的答案,增加了更多的深度; 但我需要更简单的东西,更像是 JavaScript console.log()
命令。
我在 Ajax 应用程序中的许多“收集数据并转换为 XML”中使用 PHP。 JavaScript console.log
在这种情况下不起作用; 它破坏了 XML 输出。
Xdebug 等也有类似的问题。
我在 Windows 中的解决方案:
.txt
文件.ini
文件中设置 PHP error_log
变量以写入该文件error_log('myTest');
PHP命令发送消息这个解决方案很简单,大部分时间都能满足我的需求。 标准 PHP,每次 PHP 写入时预览窗格都会自动更新。
我觉得这很有帮助:
function console($data, $priority, $debug)
{
if ($priority <= $debug)
{
$output = '<script>console.log("' . str_repeat(" ", $priority-1) . (is_array($data) ? implode(",", $data) : $data) . '");</script>';
echo $output;
}
}
并像这样使用它:
<?php
$debug = 5; // All lower and equal priority logs will be displayed
console('Important', 1 , $debug);
console('Less Important', 2 , $debug);
console('Even Less Important', 5 , $debug);
console('Again Important', 1 , $debug);
?>
在控制台输出:
Important Less Important Even Less Important Again Important
您可以通过使用 $debug 值限制不太重要的日志来关闭它们。
简短易行,适用于数组、字符串或对象。
function console_log( $data ) {
$output = "<script>console.log( 'PHP debugger: ";
$output .= json_encode(print_r($data, true));
$output .= "' );</script>";
echo $output;
}
对于 Chrome,有一个名为Chrome Logger的扩展,允许记录 PHP 消息。
Firefox DevTools 甚至集成了对 Chrome Logger 协议的支持。
要启用日志记录,您只需在项目中保存“ChromePhp.php”文件。 然后它可以像这样使用:
include 'ChromePhp.php';
ChromePhp::log('Hello console!');
ChromePhp::log($_SERVER);
ChromePhp::warn('something went wrong!');
取自GitHub 页面的示例。
输出可能如下所示:
function phpconsole($label='var', $x) {
?>
<script type="text/javascript">
console.log('<?php echo ($label)?>');
console.log('<?php echo json_encode($x)?>');
</script>
<?php
}
如果您想写入 PHP 日志文件,而不是 JavaScript 控制台,您可以使用以下命令:
error_log("This is logged only to the PHP log")
参考: error_log
还有一个很棒的 Google Chrome 扩展程序PHP Console ,它带有一个 PHP 库,可以让您:
error file:line
。我正在寻找一种方法来调试我正在开发的 WordPress 插件中的代码,并看到了这篇文章。
我从其他回复中提取了最适合我的代码,并将它们组合成一个函数,我可以用它来调试 WordPress。 功能是:
function debug_log($object=null, $label=null, $priority=1) {
$priority = $priority<1? 1: $priority;
$message = json_encode($object, JSON_PRETTY_PRINT);
$label = "Debug" . ($label ? " ($label): " : ': ');
echo "<script>console.log('" . str_repeat("-", $priority-1) . $label . "', " . $message . ");</script>";
}
用法如下:
$txt = 'This is a test string';
$sample_array = array('cat', 'dog', 'pig', 'ant', 'fly');
debug_log($txt, '', 7);
debug_log($sample_array);
如果此函数用于WordPress开发,则该函数应放在子主题的functions.php
文件中,然后可以在代码中的任何位置调用。
这是我的解决方案,这个解决方案的好处是您可以传递任意数量的参数。
function console_log()
{
$js_code = 'console.log(' . json_encode(func_get_args(), JSON_HEX_TAG) .
');';
$js_code = '<script>' . $js_code . '</script>';
echo $js_code;
}
这样称呼
console_log('DEBUG>>', 'Param 1', 'Param 2');
console_log('Console DEBUG:', $someRealVar1, $someVar, $someArray, $someObj);
现在您应该能够在控制台中看到输出,编码愉快:)
我已经放弃了上述所有内容,转而使用Debugger & Logger 。 我不能赞美它!
只需单击右上角的选项卡之一,或单击“单击此处”即可展开/隐藏。
注意不同的“类别”。 您可以单击任何阵列来展开/折叠它。
从网页
主要特点:
- 显示全局变量($GLOBALS、$_POST、$_GET、$_COOKIE 等)
- 显示 PHP 版本和加载的扩展
- 替换 PHP 内置的错误处理程序
- 记录 SQL 查询
- 监控代码和 SQL 查询执行时间
- 检查变量的变化
- 函数调用跟踪
- 代码覆盖率分析以检查执行了哪些脚本行
- 转储所有类型的变量
- 带有代码荧光笔的文件检查器以查看源代码
- 将消息发送到 JavaScript 控制台(仅限 Chrome),用于 Ajax 脚本
截至 2017 年,Firebug 和 FirePHP 已被禁用。
我对 ChromePHP 工具进行了一些小的修改,以允许从 FirePHP 无缝迁移到 Firebug,以便通过控制台进行调试。
这篇文章用清晰简单的步骤解释了
对于 Ajax 调用或 XML / JSON 响应,您不想弄乱正文,您需要通过 HTTP 标头发送日志,然后使用 Web 扩展将它们添加到控制台。 这就是 FirePHP(不再可用)和 QuantumPHP(ChromePHP 的一个分支)在 Firefox 中的工作方式。
如果您有耐心,x-debug 是更好的选择 - 您可以更深入地了解 PHP,能够暂停脚本,查看发生了什么,然后恢复脚本。
我参加聚会可能会迟到,但我正在寻找一种日志记录功能的实现,它:
console.log()
,console.log()
。所以输出看起来像这样:
(下面的代码段在 php 7.2.11
上进行了测试。我不确定它的 php 向后兼容性。它也可能是 javascript 的问题(在旧浏览器中),因为它在console.log()
之后创建了一个尾随逗号console.log()
参数——直到ES 2017
才合法。)
<?php
function console_log(...$args)
{
$args_as_json = array_map(function ($item) {
return json_encode($item);
}, $args);
$js_code = "<script>console.log('%c 💬 log from PHP: ','background: #474A8A; color: #B0B3D6; line-height: 2',";
foreach ($args_as_json as $arg) {
$js_code .= "{$arg},";
}
$js_code .= ")</script>";
echo $js_code;
}
$list = ['foo', 'bar'];
$obj = new stdClass();
$obj->first_name = 'John';
$obj->last_name = 'Johnson';
echo console_log($list, 'Hello World', 123, $obj);
?>
干净、快速、简单,没有无用的代码:
function consolelog($data) {
echo "<script>console.log('".$data."');</script>";
}
这两个中的任何一个都在工作:
<?php
$five = 5;
$six = 6;
?>
<script>
console.log(<?php echo $five + $six ?>);
</script>
<?php
$five = 5;
$six = 6;
echo("<script>console.log($five + $six);</script>");
?>
这是一个方便的功能。 它使用起来非常简单,允许您传递任意类型的任意数量的参数,并将在浏览器控制台窗口中显示对象内容,就像您从 JavaScript 调用 console.log 一样 - 但来自 PHP
请注意,您也可以通过传递“TAG-YourTag”来使用标签,它会一直应用,直到读取另一个标签,例如,“TAG-YourNextTag”
/*
* Brief: Print to console.log() from PHP
*
* Description: Print as many strings,arrays, objects, and
* other data types to console.log from PHP.
*
* To use, just call consoleLog($data1, $data2, ... $dataN)
* and each dataI will be sent to console.log - note
* that you can pass as many data as you want an
* this will still work.
*
* This is very powerful as it shows the entire
* contents of objects and arrays that can be
* read inside of the browser console log.
*
* A tag can be set by passing a string that has the
* prefix TAG- as one of the arguments. Everytime a
* string with the TAG- prefix is detected, the tag
* is updated. This allows you to pass a tag that is
* applied to all data until it reaches another tag,
* which can then be applied to all data after it.
*
* Example:
*
* consoleLog('TAG-FirstTag', $data, $data2, 'TAG-SecTag, $data3);
*
* Result:
* FirstTag '...data...'
* FirstTag '...data2...'
* SecTag '...data3...'
*/
function consoleLog(){
if(func_num_args() == 0){
return;
}
$tag = '';
for ($i = 0; $i < func_num_args(); $i++) {
$arg = func_get_arg($i);
if(!empty($arg)){
if(is_string($arg) && strtolower(substr($arg, 0, 4)) === 'tag-'){
$tag = substr($arg, 4);
}else{
$arg = json_encode($arg, JSON_HEX_TAG | JSON_HEX_AMP );
echo "<script>console.log('" . $tag . " " . $arg . "');</script>";
}
}
}
}
注意: func_num_args()和func_num_args()是 PHP 函数,用于读取动态数量的输入参数,并允许该函数从一个函数调用中获得无限多个 console.log 请求。
虽然这是一个老问题,但我一直在寻找这个。 这是我在这里回答的一些解决方案的汇编以及在其他地方找到的一些其他想法,以获得一刀切的解决方案。
代码 :
// 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');
解释 :
函数console($data, $is_error, $file, $fn)
将字符串或数组作为第一个参数,并使用 js 插入将其发布到控制台上。
第二个参数是区分正常日志和错误的标志。 对于错误,我们正在添加事件侦听器,以便在抛出任何错误时通过警报通知我们,并在控制台中突出显示。 此标志默认为 false。
第三和第四个参数是文件和行号的显式声明,这是可选的。 如果不存在,它们默认使用预定义的 php 函数debug_backtrace()
为我们获取它们。
下一个函数exceptions_to_console($svr, $str, $file, $ln)
按照 php 默认异常处理程序调用的顺序有四个参数。 在这里,第一个参数是severity,我们使用函数severity_tag($code)
与预定义的常量进一步交叉检查,以提供有关错误的更多信息。
注意 :
上面的代码使用了旧浏览器中没有的 JS 函数和方法。 为了与旧版本兼容,它需要更换。
上面的代码用于测试环境,您可以单独访问该站点。 不要在实时(生产)网站中使用它。
建议:
第一个函数console()
抛出了一些通知,所以我将它们包装在另一个函数中并使用错误控制运算符“@”调用它。 如果您不介意这些通知,则可以避免这种情况。
最后但并非最不重要的是,在编码时弹出警报可能会很烦人。 为此,我使用此哔声(在解决方案中找到: https : //stackoverflow.com/a/23395136/6060602 )而不是弹出式警报。 这非常酷,而且可能性无穷无尽,您可以播放自己喜欢的曲调并减轻编码压力。
用:
function console_log($data) {
$bt = debug_backtrace();
$caller = array_shift($bt);
if (is_array($data))
$dataPart = implode(',', $data);
else
$dataPart = $data;
$toSplit = $caller['file'])) . ':' .
$caller['line'] . ' => ' . $dataPart
error_log(end(split('/', $toSplit));
}
简短而简单的printf
和json_encode
:
function console_log($data) {
printf('<script>console.log(%s);</script>', json_encode($data));
}
我认为最好的解决方案是使用error_log(content)
这是输出
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.