开发者

How can I write to the console in PHP?

开发者 https://www.devze.com 2023-01-27 14:31 出处:网络
Is it possible write a string or log into the console? What I mean Just like in JSP, if we print somethi开发者_JS百科ng like system.out.println(\"some\"), it will be there at the console, not at a p

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

What I mean

Just like in JSP, if we print somethi开发者_JS百科ng like system.out.println("some"), it will be there at the console, not at a page.


Or you use the trick from PHP Debug to console.

First you need a little PHP helper function

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


Firefox

On Firefox you can use an extension called FirePHP which 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.

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

Chrome

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

More recently Clockwork is 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 4 and Slim 2 and support can be added via its extensible API.

Using 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.

  • Chrome - Xdebug Helper
  • Firefox - The easiest Xdebug
  • Opera - Xdebug
  • Safari - Xdebug Toggler


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

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


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_log for logging and various I/O streams can be written to with fwrite.


Try the following. It is working:

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


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 check if the variable type is unnecessary and add a buffer to solve problems with frameworks. There not have a solid return or excessive usage of 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:

How can I write to the console in PHP?


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

PHP and JavaScript interaction.


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

console.log()

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


I think it can be used --

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


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

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

Xdebug, etc. had similar issues.

My solution in Windows:

  • Setup a .txt file that is somewhat easily to get to and writable
  • Set the PHP error_log variable in the .ini file to write to that file
  • Open the file in Windows File Explorer and open a preview pane for it
  • Use the error_log('myTest'); PHP command to send messages

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.


I find this helpful:

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;
    }
}

And use it like:

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

Which outputs in console:

Important
 Less Important
     Even Less Important
Again Important

And you can switch off less important logs by limiting them using the $debug value.


Short and easy, for arrays, strings or also objects.

function console_log( $data ) {
  $output  = "<script>console.log( 'PHP debugger: ";
  $output .= json_encode(print_r($data, true));
  $output .= "' );</script>";
  echo $output;
}


For Chrome there is an extension called Chrome Logger allowing to log PHP messages.

The Firefox DevTools even have integrated support for the Chrome Logger protocol.

To enable the logging, you just need to save the 'ChromePhp.php' file in your project. Then it can be used like this:

include 'ChromePhp.php';
ChromePhp::log('Hello console!');
ChromePhp::log($_SERVER);
ChromePhp::warn('something went wrong!');

Example taken from the GitHub page.

The output may then look like this:

How can I write to the console in PHP?


function phpconsole($label='var', $x) {
    ?>
    <script type="text/javascript">
        console.log('<?php echo ($label)?>');
        console.log('<?php echo json_encode($x)?>');
    </script>
    <?php
}


If you want write to the PHP log file, and not the JavaScript console you can use this:

error_log("This is logged only to the PHP log")

Reference: error_log


There is also a great Google Chrome extension, PHP Console, with a PHP library that allows you to:

  • See errors and exceptions in the Chrome JavaScript console and in the notification popups.
  • Dump any type of variable.
  • Execute PHP code remotely.
  • Protect access by password.
  • Group console logs by request.
  • Jump to error file:line in your text editor.
  • Copy error/debug data to the clipboard (for testers).


Here is my solution, the good thing about this one is that you can pass as many params as you like.

function console_log()
{
    $js_code = 'console.log(' . json_encode(func_get_args(), JSON_HEX_TAG) .
        ');';
    $js_code = '<script>' . $js_code . '</script>';
    echo $js_code;
}

Call it this way

console_log('DEBUG>>', 'Param 1', 'Param 2');
console_log('Console DEBUG:', $someRealVar1, $someVar, $someArray, $someObj);

Now you should be able to see output in your console, happy coding :)


I think best solution is to use error_log(content) This is output

Edit 2022:

So I’ve discovered way better way and thats file_put_contents("php://stdout", content)

It writes without the logging info


Any of these two are working:

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


I was looking for a way to debug code in a WordPress plugin that I was developing and came across this post.

I took the bits of code that are most applicable to me from other responses and combined these into a function that I can use for debugging WordPress. The function is:

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

Usage is as follows:

$txt = 'This is a test string';
$sample_array = array('cat', 'dog', 'pig', 'ant', 'fly');
debug_log($txt, '', 7);
debug_log($sample_array);

If this function is used with WordPress development, the function should be placed in the functions.php file of the child theme and can then be called anywhere in the code.


Clean, fast and simple without useless code:

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


Short and simply with printf and json_encode:

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


I have abandoned all of the above in favour of Debugger & Logger. I cannot praise it enough!

Just click on one of the tabs at top right, or on the "click here" to expand/hide.

Notice the different "categories". You can click any array to expand/collapse it.

From the web page

Main features:

  • Show globals variables ($GLOBALS, $_POST, $_GET, $_COOKIE, etc.)
  • Show PHP version and loaded extensions
  • Replace PHP built in error handler
  • Log SQL queries
  • Monitor code and SQL queries execution time
  • Inspect variables for changes
  • Function calls tracing
  • Code coverage analysis to check which lines of script where executed
  • Dump of all types of variable
  • File inspector with code highlighter to view source code
  • Send messages to JavaScript console (Chrome only), for Ajax scripts

How can I write to the console in PHP?


As of 2017, Firebug and hence FirePHP has been disabled.

I wrote some little modifications to the ChromePHP tool to allow seamless migration from FirePHP to Firebug for debugging via the console.

This article explains in clear easy steps

Migrate from FirePHP to ChromePHP in 5 minutes (without breaking existing code)


For Ajax calls or XML / JSON responses, where you don't want to mess with the body, you need to send logs via HTTP headers, then add them to the console with a web extension. This is how FirePHP (no longer available) and QuantumPHP (a fork of ChromePHP) do it in Firefox.

If you have the patience, x-debug is a better option - you get deeper insight into PHP, with the ability to pause your script, see what is going on, then resume the script.


I might be late for a party, but I was looking for an implementation of logging function which:

  • takes a variable number of comma separated arguments, just like javascript console.log(),
  • gives a formatted output (not just a serialized string),
  • is distinguishable from a common javascript console.log().

So the output looks like that:

How can I write to the console in PHP?

(The snippet below is tested on php 7.2.11. I'm not sure about its php backward compatibility. It can be an issue for javascript as well (in a term of old browsers), because it creates a trailing comma after console.log() arguments – which is not legal until ES 2017.)

<?php

function console_log(...$args)
{
    $args_as_json = array_map(function ($item) {
        return json_encode($item);
    }, $args);

    $js_code = "<script>console.log('%c 
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号