When debugging our PHP program, a common way is to print the variable information to the browser, for example: (recommended learning: PHP video tutorial)
<?php echo '<pre class="brush:php;toolbar:false">'; print_r($bar); echo ''; exit;
But printing it out directly may interfere with your page, disrupt the layout, affect the data returned as Api and other issues. At this time, we can output the debugging information to a file. The following is the simplest example:
error_log(print_r($bar, true));
However, this method is suitable for recording logs, but it is still not suitable for debugging. convenient. At this time, we can use the console of modern browsers, such as Chrome Console (Win shortcut key Ctrl Shift J), to output the content to the Console, which can solve this problem.
There are already some such tools, such as PHP-Console or Chrome Logger. The former is for PHP, and the latter supports multiple server-side languages. The method of use is to install a Chrome extension first. Then provide the server-side library for calling. The implementation method is generally to use Session, Cookies, etc. to transfer data.
The above are relatively complete solutions and provide rich functions. But if you just want a simple, usable way to solve this problem without installing an extension, then you can do it like this:
<?php function console_log($data) { if (is_array($data) || is_object($data)) { echo("<script>console.log('".json_encode($data)."');</script>"); } else { echo("<script>console.log('".$data."');</script>"); } }
It is essentially adding a javascript script to the page. Use the console.log(); function to output information to the console. The above method will print out the information in the form of strings. If the single quotes are removed, PHP arrays and objects will be printed out in the form of JS objects, that is,
echo("<script>console.log(".json_encode($data).");</script>");
The above is the detailed content of How to return data to the console in php. For more information, please follow other related articles on the PHP Chinese website!