如何在 PHP 中写入控制台?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4323411/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 12:39:59  来源:igfitidea点击:

How can I write to the console in PHP?

phpdebuggingprintingconsole

提问by Labeeb Panampullan

Is it possible write a string or log into the console?

是否可以写入字符串或登录控制台?

What I mean

我的意思是

Just like in JSP, if we print something like system.out.println("some"), it will be there at the console, not at a page.

就像在 JSP 中一样,如果我们打印类似 的内容system.out.println("some"),它将在控制台中,而不是在页面上。

采纳答案by Malachi

Firefox

火狐

On Firefox you can use an extension called FirePHPwhich enables the logging and dumping of information from your PHP applications to the console. This is an addon to the awesome web development extension Firebug.

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

Chrome

铬合金

However if you are using Chrome there is a PHP debugging tool called Chrome Loggeror webug(webug has problems with the order of logs).

但是,如果您使用的是 Chrome,则有一个名为Chrome Loggerwebug的 PHP 调试工具(webug 有日志顺序问题)。

More recently Clockworkis in active development which extends the Developer Tools by adding a new panel to provide useful debugging and profiling information. It provides out of the box support for Laravel 4and Slim 2and support can be added via its extensible API.

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

Using Xdebug

使用 Xdebug

A better way to debug your PHP would be via Xdebug. Most browsers provide helper extensions to help you pass the required cookie/query string to initialize the debugging process.

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

回答by Senador

Or you use the trick from PHP Debug to console.

或者您使用从PHP Debug 到 console的技巧。

First you need a little PHP helper function

首先你需要一个小的 PHP 辅助函数

function debug_to_console($data) {
    $output = $data;
    if (is_array($output))
        $output = implode(',', $output);

    echo "<script>console.log('Debug Objects: " . $output . "' );</script>";
}

Then you can use it like this:

然后你可以像这样使用它:

debug_to_console("Test");

This will create an output like this:

这将创建如下输出:

Debug Objects: Test

回答by Travis

If you're looking for a simple approach, echo as JSON:

如果您正在寻找一种简单的方法,请作为 JSON 回显:

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

回答by nikc.org

By default, all output goes to stdout, which is the HTTP response or the console, depending on whether your script is run by Apache or manually on the command line. But you can use error_logfor logging and various I/O streamscan be written to with fwrite.

默认情况下,所有输出都转到stdout,即 HTTP 响应或控制台,具体取决于您的脚本是由 Apache 运行还是在命令行上手动运行。但是你可以使用error_log用于记录和各种I / O流可以被写入同fwrite

回答by Mandy

Try the following. It is working:

请尝试以下操作。这是工作:

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

回答by Neo

echo 
"<div display='none'>
    <script type='text/javascript'>
        console.log('console log message');
    </script>
</div>";

Creates a

创建一个

<div>

with the

display="none"

so that the div is not displayed, but the

以便不显示 div,但

console.log()

function is created in javascript. So you get the message in the console.

函数是在javascript中创建的。所以你会在控制台中收到消息。

回答by bueltge

As the author of the linked webpage in the popular answer, I would like to add my last version of this simple helper function. It is much more solid.

作为热门答案中链接网页的作者,我想添加这个简单帮助函数的最新版本。它要坚固得多。

I use json_encode()to make a check for if the variable type is not necessary and also add a buffer to solve problems with frameworks. There not have a solid return or excessive usage of header().

我用来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;
}

Usage

用法

// $data is the example variable, object; here an array.
$data = [ 'foo' => 'bar' ];
debug_to_console($data);`

Screenshot of the result

结果截图

Also a simple example as an image to understand it much easier:

还有一个简单的例子作为图像,更容易理解:

Enter image description here

在此处输入图片说明

回答by Pankaj Bisht

I think it can be used --

我觉得可以用——

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

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

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

    echo($html);
    # 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"]}

回答by Klompenrunner

Some great answers that add more depth; but I needed something simpler and more like the JavaScript console.log()command.

一些很好的答案,增加了更多的深度;但我需要更简单更像 JavaScriptconsole.log()命令的东西。

I use PHP in a lot of "gathering data and turn into XML" in Ajax applications. The JavaScript console.logdoesn't work in that case; it breaks the XML output.

我在 Ajax 应用程序中的许多“收集数据并转换为 XML”中使用 PHP。console.log在这种情况下JavaScript不起作用;它破坏了 XML 输出。

Xdebug, etc. had similar issues.

Xdebug 等也有类似的问题。

My solution in Windows:

我在 Windows 中的解决方案:

  • Setup a .txtfile that is somewhat easily to get to and writable
  • Set the PHP error_logvariable in the .inifile to write to that file
  • Open the file in Windows File Explorerand open a preview pane for it
  • Use the error_log('myTest');PHP command to send messages
  • 设置一个.txt易于访问和可写的文件
  • error_log.ini文件中设置 PHP变量以写入该文件
  • 在 Windows文件资源管理器中打开文件并为其打开预览窗格
  • 使用error_log('myTest');PHP 命令发送消息

This solution is simple and meets my needs most of the time. Standard PHP, and the preview pane automatically updates every time PHP writes to it.

这个解决方案很简单,大部分时间都能满足我的需求。标准 PHP,每次 PHP 写入时预览窗格都会自动更新。

回答by 0DAYanc

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

PHP and JavaScript interaction.

PHP 和 JavaScript 交互。