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

我的意思是

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


当前回答

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

在Chrome JavaScript控制台和弹出的通知中看到错误和异常。 转储任何类型的变量。 远程执行PHP代码。 使用密码保护访问。 根据请求对控制台日志进行分组。 跳转到文本编辑器中的错误文件:行。 将错误/调试数据复制到剪贴板(用于测试人员)。

其他回答

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

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

结果截图

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

火狐

在Firefox上,您可以使用一个名为FirePHP的扩展,它支持从PHP应用程序记录信息并将信息转储到控制台。这是一个令人敬畏的web开发扩展Firebug的插件。

http://www.studytrails.com/blog/using-firephp-in-firefox-to-debug-php/

但是如果你使用的是Chrome浏览器,有一个PHP调试工具叫做Chrome Logger或webug (webug有日志顺序的问题)。

最近,Clockwork正在积极开发中,它通过添加一个新的面板来提供有用的调试和分析信息,扩展了开发人员工具。它为Laravel 4和Slim 2提供了开箱即用的支持,并可以通过其可扩展的API添加支持。

使用Xdebug

调试PHP的更好方法是通过Xdebug。大多数浏览器都提供了辅助扩展来帮助您传递所需的cookie/查询字符串来初始化调试过程。

Chrome - Xdebug助手 Firefox -最简单的Xdebug Opera - Xdebug Safari - Xdebug切换器

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

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

这两个都有效:

<?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>");
?>

Use:

function console_log($data) {
    $bt = debug_backtrace();
    $caller = array_shift($bt);

    if (is_array($data))
        $dataPart = implode(',', $data);
    else
        $dataPart = $data;

    $toSplit = $caller['file'])) . ':' .
               $caller['line'] . ' => ' . $dataPart

    error_log(end(split('/', $toSplit));
}