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

我的意思是

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


当前回答

如果你正在寻找一个简单的方法,echo as JSON:

<script>
    console.log(<?= json_encode($foo); ?>);
</script>

其他回答

我认为它可以被用来

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

作为热门答案中链接网页的作者,我想添加我最后一个版本的这个简单的助手功能。它更坚固。

我使用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);`

结果截图

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

对于Ajax调用或XML / JSON响应,您不想干扰主体,您需要通过HTTP报头发送日志,然后使用web扩展将它们添加到控制台。这就是FirePHP(不再可用)和QuantumPHP (ChromePHP的一个分支)在Firefox中的做法。

如果您有耐心,x-debug是一个更好的选择—您可以更深入地了解PHP,能够暂停脚本,查看正在发生的事情,然后恢复脚本。

$variable = "Variable";
echo "<script>console.log('$variable');</script>";

PHP和JavaScript交互。

如果你正在寻找一个简单的方法,echo as JSON:

<script>
    console.log(<?= json_encode($foo); ?>);
</script>