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

我的意思是

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


当前回答

在开始代码中…

error_reporting(-1);
ini_set('display_errors', 'On'); 

它的工作

其他回答

简单的printf和json_encode:

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

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

在Chrome JavaScript控制台和弹出的通知中看到错误和异常。 转储任何类型的变量。 远程执行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);
?>

在控制台输出:

重要的 不那么重要 更不重要 同样重要的

您可以通过使用$debug值限制不太重要的日志来关闭它们。

对于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 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"]}