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

我的意思是

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


当前回答

我正在寻找一种方法来调试我正在开发的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文件中,然后可以在代码的任何地方调用。

其他回答

简单的printf和json_encode:

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

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

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

或者使用从PHP调试到控制台的技巧。

首先需要一个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

干净、快速、简单,没有无用的代码:

function consolelog($data) {
    echo "<script>console.log('".$data."');</script>";
}

我正在寻找一种方法来调试我正在开发的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文件中,然后可以在代码的任何地方调用。