是否可以写入字符串或登录到控制台?
就像在jsp中一样,如果我们打印类似system.out.println("some")
的内容,它将在控制台上而不是在页面上。
答案 0 :(得分:326)
或者您使用本网站的技巧 PHP Debug to 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
答案 1 :(得分:131)
<强>火狐强>
在Firefox上,您可以使用名为FirePHP的扩展程序,该扩展程序可以将PHP应用程序中的信息记录和转储到控制台。这是令人敬畏的Web开发扩展Firebug的插件。
<强>铬强>
但是,如果您使用Chrome,则会有一个名为Chrome Logger或webug的PHP调试工具(webug在日志顺序方面存在问题)。
最近Clockwork处于活跃开发阶段,通过添加新面板来扩展Developer Tools,以提供有用的调试和分析信息。它为Laravel 4和Slim 2提供了现成的支持,并且可以通过其可扩展的API添加支持。
使用Xdebug
调试PHP的更好方法是通过Xdebug。大多数浏览器都提供帮助程序扩展,以帮助您传递所需的cookie /查询字符串以初始化调试过程。
答案 2 :(得分:61)
如果您正在寻找一种简单的方法,请回显为JSON:
<script>
console.log(<?= json_encode($foo); ?>);
</script>
答案 3 :(得分:35)
默认情况下,所有输出都转到stdout
,这是HTTP响应或控制台,具体取决于您的脚本是由Apache运行还是在命令行上手动运行。但您可以使用error_log
进行日志记录,various I/O streams可以使用fwrite
写入。{/ p>
答案 4 :(得分:33)
尝试这样做是有效的:
echo("<script>console.log('PHP: ".$data."');</script>");
答案 5 :(得分:16)
echo
"<div display='none'>
<script type='text/javascript'>
console.log('console log message');
</script>
</div>";
创建
<div>
使用
display="none"
这样就不会显示div,而是显示
console.log()
函数在javascript中创建。所以你在控制台中收到消息。
答案 6 :(得分:14)
一些增加更多深度的好答案;但我需要更简单的东西,更像是JS console.log()
命令。
我在AJAX应用程序中使用PHP进行了很多“收集数据并转换成xml”。 JS console.log
在这种情况下不起作用;它打破了xml输出。 (也许有人有解决方案?)
Xdebug等也有类似的问题。
我在Windows中的解决方案:
.txt
文件error_log
文件中设置PHP .ini
变量以写入该文件error_log('myTest');
PHP命令发送消息此解决方案很简单,大部分时间都符合我的需求,标准PHP,每次PHP写入时预览窗格都会自动更新。
答案 7 :(得分:14)
作为上面popular answer的链接网页的作者,我想添加这个简单帮助函数的最后一个版本,更加可靠。
我使用json_encode()
来检查不必要的var类型,并添加一个缓冲区来解决框架问题,没有可靠的返回或过度使用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 var, object; here an array.
$data = [ 'foo' => 'bar' ];
debug_to_console( $data );`
这也是一个简单的例子,因为图像可以更容易理解。
答案 8 :(得分:13)
我认为可以使用它 -
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 Array
jsLogs(array("test1", "test2")); # PHP: ["test1","test2"]
# For Object
jsLogs(array("test1"=>array("subtest1", "subtest2"))); #PHP: {"test1":["subtest1","subtest2"]}
# For String
jsLogs("testing string"); #PHP: testing string
答案 9 :(得分:11)
我觉得这很有帮助:
function console($data, $priority, $debug)
{
if ($priority <= $debug)
{
if (is_array($data))
$output = '<script>console.log("' . str_repeat(" ", $priority-1) . implode( ",", $data) . '");</script>';
else
$output = '<script>console.log("' . str_repeat(" ", $priority-1) . $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 value限制它们来关闭不太重要的日志
答案 10 :(得分:10)
$variable = "Variable";
echo "<script>console.log('$variable');</script>";
PHP和Javascript交互。
答案 11 :(得分:8)
对于数组,字符串或对象来说简单易行。
function console_log( $data ) {
$output = "<script>console.log( 'PHP debugger: ";
$output .= json_encode(print_r($data, true));
$output .= "' );</script>";
echo $output;
}
答案 12 :(得分:7)
function phpconsole($label='var',$x){
?>
<script type="text/javascript">
console.log('<?php echo ($label)?>');
console.log('<?php echo json_encode($x)?>');
</script>
<?php
}
答案 13 :(得分:6)
如果要写入PHP日志文件而不是JavaScript控制台,可以使用:
error_log ( "This is logged only to the PHP log" )
答案 14 :(得分:5)
对于Chrome,有一个名为Chrome Logger的扩展程序,允许记录PHP消息。
Firefox DevTools甚至有integrated support for the Chrome Logger protocol。
要启用日志记录,只需在项目中保存'ChromePhp.php' file即可。然后就可以这样使用:
include 'ChromePhp.php';
ChromePhp::log('Hello console!');
ChromePhp::log($_SERVER);
ChromePhp::warn('something went wrong!');
取自GitHub page。
的示例输出可能如下所示:
答案 15 :(得分:5)
还有一个很棒的Google Chrome扩展程序PHP Console,php library允许:
答案 16 :(得分:3)
很棒的帖子谢谢你,我正在寻找一种方法来调试我正在开发的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文件中,然后可以在代码中的任何位置调用。
答案 17 :(得分:3)
我放弃了所有上述内容而赞成http://phptoolcase.com/guides/ptc-debug-guide.html我不能赞美它!
只需点击右上角的其中一个标签,或点击“点击此处”即可展开/隐藏。
注意不同的“类别”。您可以单击任何阵列来展开/拼接它。
Fromn the web page
“主要特点:
Show globals vars ($GLOBALS, $_POST, $_GET, $_COOKIE ...)
Show php version and loaded extensions
Replace php built in error handler
Log sql queries
Monitor code and sql queries execution time
Inspect variables for changes
Function calls tracing
Code coverage analysis to check which lines of script where executed
Dump of all types of variable
File inspector with code highlighter to view source code
Send messages to js console(Chrome only), for ajax scripts
”
答案 18 :(得分:3)
这是我的解决方案,关于这一点的好处是您可以根据需要传递尽可能多的参数。
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);
现在,您应该可以在控制台中看到输出了,编码愉快:)
答案 19 :(得分:2)
截至2017年,萤火虫和firephp已被禁用。
我对chromephp工具做了一些修改,允许从firephp无缝迁移到firebug,以便通过控制台进行debuging。
本文以简单易懂的步骤解释
答案 20 :(得分:2)
对于Ajax调用或xml / json响应,您不希望弄乱正文,您需要通过http标头发送日志,然后使用Web扩展将它们添加到控制台。这就是FirePHP和QuantumPHP(ChromePHP的一个分支)在Firefox中的功能。
如果你有耐心,x-debug是一个更好的选择 - 你可以更深入地了解PHP,能够暂停你的脚本,看看发生了什么,然后恢复脚本。
答案 21 :(得分:2)
我可能要参加一个聚会,但是我正在寻找一种记录功能的实现,
console.log()
一样,console.log()
有所区别。所以输出看起来像这样:
(下面的代码段已在php 7.2.11
上进行了测试。我不确定它的php向后兼容性。这对于javascript也可能是一个问题(在旧版浏览器中),因为它会创建一个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);
?>
答案 22 :(得分:1)
这两个中的任何一个都在起作用:
<?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>");
?>
答案 23 :(得分:1)
尽管这是一个古老的问题,但我一直在寻找。这是我在此处回答的一些解决方案的汇编,以及在别处找到的其他一些想法,以获得一种千篇一律的解决方案。
代码:
// 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');
EXPLANATION:
函数console($data, $is_error, $file, $fn)
将字符串或数组作为第一个参数,并使用js插入程序将其发布到控制台上。
第二个参数是一个标志,用于区分普通日志和错误。对于错误,我们添加了事件侦听器,以通过警报通知我们是否抛出任何错误,并在控制台中突出显示。此标志默认为false。
第三和第四个参数是文件和行号的显式声明,这是可选的。如果不存在,默认情况下它们将使用预定义的php函数debug_backtrace()
为我们获取它们。
下一个函数exceptions_to_console($svr, $str, $file, $ln)
按php默认异常处理程序调用的顺序具有四个参数。在这里,第一个参数是严重性,我们使用功能severity_tag($code)
与预定义的常量进行交叉检查,以提供有关错误的更多信息。
注意:
以上代码使用了旧版浏览器中不提供的JS函数和方法。为了与旧版本兼容,需要替换。
以上代码用于测试环境,您一个人就可以访问该网站。请勿在实时(生产)网站中使用它。
建议:
第一个函数console()
发出了一些通知,因此我将它们包装在另一个函数中,并使用错误控制运算符'@'对其进行了调用。如果您不注意通知,可以避免这种情况。
最后但并非最不重要的是,在编码时弹出的警报可能会令人讨厌。为此,我使用了蜂鸣声(在解决方案中:https://stackoverflow.com/a/23395136/6060602)而不是弹出警报。这很酷,可能性无穷无尽,您可以播放自己喜欢的音乐并减轻编程压力。
答案 24 :(得分:1)
干净、快速、简单,没有无用的代码:
function consolelog($data) {
echo "<script>console.log('".$data."');</script>";
}
答案 25 :(得分:0)
function console_log( $data ) {
$bt = debug_backtrace();
$caller = array_shift($bt);
if ( is_array( $data ) )
error_log( end(split('/',$caller['file'])) . ':' . $caller['line'] . ' => ' . implode( ',', $data) );
else
error_log( end(split('/',$caller['file'])) . ':' . $caller['line'] . ' => ' . $data );
}
答案 26 :(得分:0)
这是一个方便的功能。它使用起来超级简单,允许您传递任意数量的任意类型的参数,并且将在浏览器控制台窗口中显示对象内容,就像您从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()是用于读取动态数量的输入args的php函数,并允许该函数具有无限多个console.log请求通过一个函数调用
答案 27 :(得分:0)
简短而简单的 printf
和 json_encode
:
function console_log($data) {
printf('<script>console.log(%s);</script>', json_encode($data));
}
答案 28 :(得分:0)
我认为最好的解决方案是使用
error_log(content)
This is output
答案 29 :(得分:0)