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

我的意思是

就像在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);`

结果截图

另外,一个简单的例子作为一个图像,更容易理解它:

其他回答

简单的printf和json_encode:

function console_log($data) {
    printf('<script>console.log(%s);</script>', json_encode($data));
}

我认为它可以被用来

function jsLogs($data, $isExit) {
    $html = "";
    $coll;

    if (is_array($data) || is_object($data)) {
        $coll = json_encode($data);
    } else {
        $coll = $data;
    }

    $html = "<script id='jsLogs'>console.log('PHP: ${coll}');</script>";

    echo($html);

    if ($isExit) 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一样——但是从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请求。

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

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

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

代码:

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