php print to console
Как я могу писать в консоль на PHP?
можно ли записать строку или войти в консоль?
что я имею в виду
Так же, как в jsp, если мы печатаем что-то вроде system.out.println(«some») Он будет там на консоли, а не на странице.
23 ответов:
в Firefox вы можете использовать расширение под названием FirePHP что позволяет регистрировать и сбрасывать информацию из ваших PHP-приложений на консоль. Это аддон к удивительному расширению веб-разработки Firebug.
Chrome
однако, если вы с помощью Chrome есть инструмент отладки PHP под названием Chrome Logger или webug (webug имеет проблемы с заказом журналов).
совсем недавно часам находится в активной разработке, которая расширяет инструменты разработчика, добавляя новую панель для предоставления полезной информации об отладке и профилировании. Он обеспечивает из коробки поддержку Laravel 4 и Slim 2 и поддержка может быть добавлена через расширяемый API.
С Помощью Xdebug
лучший способ отладки PHP будет через Xdebug. Большинство браузеров предоставляют вспомогательные расширения, чтобы помочь вам передать необходимую строку cookie / query для инициализации процесса отладки.
сначала вам нужно немного PHP вспомогательная функция
тогда вы можете использовать его так
Это создаст выход, как это:
Если вы ищете простой подход, echo как JSON:
Я использую PHP во многих «сбор данных и превращение в xml» в приложении AJAX. JS console.log не работает в этом случае; он нарушает вывод xml. (Может быть, у кого-то есть решение для этого?)
отладчик xdebug и т. д. были подобные вопросы.
мое решение в Windows:
это решение простое, отвечает моим потребностям больше всего времени, стандартный PHP, и панель предварительного просмотра автоматически обновляется каждый раз, когда PHP пишет на него.
как автор связанной веб-страницы int the популярный ответ выше я хотел бы добавить мою последнюю версию этой простой вспомогательной функции, гораздо более твердый.
использование
скриншот результата
также простой пример как изображение понять гораздо проще.
и использовать его как:
, который выводит в консоль:
так что div не отображается, но
функция создается в javascript. Таким образом, вы получаете сообщение в консоли.
Printing debug output to console in Codeception
Very thick question, but is there any way to print your own debug messages to the console in Codeception? I mean messages that have nothing to do with assertions, purely for debugging the tests themselves (e.g. like you would var_dump() a variable in any regular PHP website)
9 Answers 9
You may print any information inside a test using the codecept_debug function.
And I’m using it in my *Cept class:
And the output looked like:
I seem to have found a way around the issue by using a helper class:
and calling the class as such:
then I get the debug output I’m looking for
I will accept this as a temporary solution however I would like to keep my assertions clean and not clutter them with var_dumps upgraded to test functions, so if anyone has a conceptually correct solution, please submit
Or you can use the verbosity controlling commands like:
where each v increases the verbosity of the output (very silent by default).
Just call ob_flush() after outputting text
Example code:
Screenshot of code and output:
Why? PHPUnit is always output buffering, so we need to dump the buffer when debugging
I was reading the PHPUnit manual like a good nerd and stumbled onto this, which I think explains what causes this whole issue across all of PHPUnit, not just Codeception:
PHPUnit manual, Testing Output: “Sometimes you want to assert that the execution of a method, for instance, generates an expected output (via echo or print, for example). The PHPUnit\Framework\TestCase class uses PHP’s Output Buffering feature to provide the functionality that is necessary for this.”
But when we’re debugging, we just want to see the text right away, and understanding all this, the solution is clear: Just use ob_flush() to print the contents of the output buffer on demand!
How to Log to Console in PHP
PHP is one of the most popular server-side scripting languages for building web applications because it’s easy to use. No matter what you build, making it easy to log errors is key to ensuring a short code-test-learn feedback cycle. Because PHP was developed way before today’s modern browsers, it didn’t really have an easy way to log errors to the browser console—even though the browser is the main way to interact with websites and web applications and PHP is uniquely designed to be good for building web applications. Using JavaScript, logging to console is as simple as this:
In this article, I will show you how to log to console within PHP, why logging in PHP can be a good thing, and how it’s just as easy as logging to console using JavaScript. So you can have the best of both worlds: enjoy the power and ease of a great web programming language like PHP andstill log to console within PHP.
What is the browser console?
First of all, we need to understand what the browser console is.
The browser console is a way for the browser to log information associated with a specific web page. The information logged includes network requests, JavaScript, CSS, security errors, and warnings as well as error, warning, and informational messages explicitly logged by JavaScript code running in the page context.
For the rest of this article, I’ll be using desktop Google Chrome for demonstration. You can actually perform similar steps in modern browsers like the desktop versions of Firefox, Safari, and Internet Explorer. When you open Google Chrome and go to any web page, right-click, and choose Inspect, you’ll bring up Chrome’s Developer Tools.
Fig. 1: How to trigger Developer Tools in Chrome
Fig. 2: Developer Tools in Chrome after clicking on Inspect
The browser console will be one of the tabs in the Developer Tools. And you can test it out by writing the same JavaScript console.log command.
Fig. 3: How to log to console using JavaScript
Why logging to console is a good thing
There are two primary reasons you want to log to the browser console.
The first is simplicity. As a PHP developer, you want to work with, at most, two applications: your favorite code editor or IDE and your browser. You toggle between the two as you write code in the editor and test it on the browser. The most natural place to display log statements is inside the browser.
The second reason is to keep the logging as least intrusive as possible. Now, you can log using PHP’s native functions such as var_dump. However, when you use var_dump, you need to decide where you want to write the output to. It could be the browser web page, but this will likely distort the display. Another possible destination for output may be a file in your server, for which I’d recommend an open-source logging library like monolog instead of var_dump. If you prefer to output view variables (e.g., variables that are more related to display) and don’t want to distort the web page, logging to the browser console might be a better idea.
Another thing to note is that, increasingly, PHP developers gravitate toward frameworks such as Laravel and Symfony, which usually use popular PHP logging libraries such as monolog. These libraries work best when you want a detailed breakdown of the error stack trace for server-side errors such as database connection and outputting these into files. By the way, Stackify’s tutorials also cover monolog logging for such situations, where you can learn how to send the logs to Retrace.
Sometimes you just want something lightweight to display inside the browser for front-end debugging. For such situations, logging to console would be ideal. Furthermore, you can combine this technique with the standard PHP logging methods for a more complete development setup.
How to log directly to console using PHP code
There are two main ways you can log directly to the console using (mostly) PHP code. I can summarize it as using json_encode function and using PHP libraries.
Using json_encode function
Let’s say you want to console log a PHP variable $view_variable in your view layer. Recall that console.log is a JavaScript function. The key principle is that we can make use of JSON to pass the PHP variable to the JavaScript function. You create a PHP function like this:
You can call this function at exactly the place you want to run the console_log that we just created, as seen above. An example of its usage would look like this:
And the generated HTML markup would be this:
As long as you remember to include the definition of the customized console_log PHP function, you can call it as many times as you need to. If you prefer to transform the JSON string into other forms, you can reference the list of constants that json_encode uses. The useful constants that you’re more likely to use are JSON_FORCE_OBJECT and JSON_PRETTY_PRINT.
Logging in the middle of your JavaScript code
Sometimes, you don’t want to install PHP libraries only when you’re absolutely sure you have to. So, you might prefer to console log the PHP variables in the middle of your JavaScript code found in your PHP view files. You can make use of the same technique this way:
Using PHP libraries to console log
If you prefer to use open-source libraries that have solved this issue, there are two candidates I recommend. They are PHPDebugConsole (installation instructions and code here) and PHPConsole (installation instructions and code here).
A comparison between PHPDebugConsole and PHPConsole
A quick comparison between the two libraries yields the following analysis.
PHPConsole appears to be more established with 1,191 stars on its GitHub repo, while PHPDebugConsole has fewer than 30 stars. At the time of writing, PHPConsole hasn’t been updated since late 2018 and has fewer commits (128) compared with PHPDebugConsole at 256 commits. PHPDebugConsole has a more frequent update history with the last three commits all happening in January 2019. PHPDebugConsole also has better documentation. Their documentation explicitly recommends several browser extensions that it can work with and includes demo examples. PHPConsole, on the other hand, recommends a Chrome Extension that seems to be authored by the same people behind PHPConsole. However, their demo website is not working as of the time I’m writing this.
Taking all the above into consideration, I have to recommend choosing PHPDebugConsole if you want to use a PHP library to console log. Overall, I’d recommend the following decision matrix:
An example from PHPDebugConsole
Here’s an example taken from PHPDebugConsole’s excellent demo website:
true, // turn logging on
‘output’ => true, // if left false (default), the output() method will return an empty string
));
public function __toString() <
return ‘It\’s Magic’;
>
$debug->info(‘PHPDebugConsole is great!’);
$debug->warn(‘No browser plugin necessary’);
$debug->log(‘features/options’, array(
‘PHP port of the javascript web console API’,
‘outputOpts’ => array(
‘HTML (as seen here)’,
‘ChromeLogger’,
‘FirePHP’,
‘Plain-text / file’,
‘
(PHP 4, PHP 5, PHP 7, PHP 8)
print — Выводит строку
Описание
Список параметров
Возвращаемые значения
Примеры
Пример #1 Примеры использования print
print «print не требует скобок.» ;
// Новая строка или пробел не добавляются; ниже выводит «приветмир» в одну строку
print «привет» ;
print «мир» ;
print «Эта строка занимает
несколько строк. Новые строки
также будут выведены» ;
print «Эта строка занимает\nнесколько строк. Новые строки\nтакже будут выведены» ;
// Нестроковые выражения приводятся к строковым, даже если используется declare(strict_types=1)
print 6 * 7 ; // 42
// Поскольку print имеет возвращаемое значение, его можно использовать в выражениях
// Следующие выходные данные «привет мир»
if ( print «привет» ) <
echo » мир» ;
>
Примечания
Замечание: Использование с круглыми скобками
print «привет» ;
// выведет «привет»
print( 1 + 2 ) * 3 ;
// выведет «9»; круглые скобки приводят к тому, что сначала вычисляется 1+2, а затем 3*3
// оператор print видит все выражение как один аргумент
При использовании print в более крупном выражении может потребоваться размещение ключевого слова и его аргумента в круглых скобках для получения желаемого результата:
print «привет » && print «мир» ;
// выведет «мир1»; print «мир» выполняется в первую очередь,
// тогда выражение «привет» && 1 передается в левую часть print
(print «привет » ) && (print «мир» );
// выведет «привет мир»; круглые скобки заставляют выражения print
// выполнятьтся перед &&
?>
Замечание: Поскольку это языковая конструкция, а не функция, она не может вызываться при помощи переменных функций.
Смотрите также
User Contributed Notes 9 notes
Be careful when using print. Since print is a language construct and not a function, the parentheses around the argument is not required.
In fact, using parentheses can cause confusion with the syntax of a function and SHOULD be omited.
Most would expect the following behavior:
if (print( «foo» ) && print( «bar» )) <
// «foo» and «bar» had been printed
>
?>
But since the parenthesis around the argument are not required, they are interpretet as part of the argument.
This means that the argument of the first print is
and the argument of the second print is just
For the expected behavior of the first example, you need to write:
if ((print «foo» ) && (print «bar» )) <
// «foo» and «bar» had been printed
>
?>
Running in a browser:
Running in a shell:
the FAQTs article can be found archived at http://web.archive.org/web/20060601063513/http
://www.faqts.com/knowledge_base/view.phtml/aid/1/fid/40
(url split to get past the line-length limitation)
mvpetrovich of 2007 could just use single quotes as his string delimiters (see the example in the current documentation).
It’s not ALWAYS appropriate, but generally it is best (the Zend Framework coding standards have a good take on this). It yields a number of interesting benefits:
1: Nobody will be tempted to write functions to replace backticks or other characters with double quotes. Such functions may cause a (negligible) loss of efficiency, and maybe other undesired effects.
2: You will be able to use double quotes without escaping. This is recommended (although not required) for HTML and XML attributes, as well as quoted text.
3: The script will hit the browser very slightly slightly faster since PHP doesn’t have to scan through the string looking for variables, escaped characters, curly braces or other things.
4: Your code gets ten times easier to read. (as mvpetrovich pointed out)
If, in spite of these four excellent benefits, you really MUST still use double quotes to delimit boring old string constants (and seriously, why would you?), you could use the slightly less favourable single quotes as delimiters for most markup languages.
HTML served as HTML will even let you lay out unquoted attributes (yuck).
It should also be noted though that if you are just printing bare strings, you may as well shut off the php parser. The quickest way to send a string is to write it as plain text, OUTSIDE of the php tags. This will also make your code look excellent in a lot of syntax highlighters.
There are few disadvantages to doing this, if any. Output buffering still works. All your classes and objects and includes remain in place. Your script runs faster. World peace is obtained.
I have a small utility run from the command line that processes a potentially huge list of files. As it can take hours to complete, I stuck a
statement in the body of the main loop to prove that something was happening.
For reasons unknown to me, the utiliity suddenly started buffering the output such that it printed nothing until completion, defeating the purpose of the running monitor. Adding flush() statements did nothing. The problem was solved by using
but I have no idea why.
Don’t rely on parenthesis used for `print` construct:
I have written a script to benchmark the several methods of outputting data in PHP: via single quotes, double quotes, heredoc, and printf. The script constructs a paragraph of text with each method. It performs this construction 10,000 times, then records how long it took. In total, it prints 160,000 times and records 16 timings. Here are the raw results.
Outputted straight to browser—
Single quotes: 2,813 ms
. with concatenation: 1,179 ms
Double quotes: 5,180 ms
. with concatenation: 3,937 ms
heredoc: 7,300 ms
. with concatenation: 6,288 ms
printf: 9,527 ms
. with concatenation: 8,564 ms
Outputted to the output buffer—
Single quotes: 8 ms
. with concatenation: 38 ms
Double quotes: 8 ms
. with concatenation: 47 ms
heredoc: 17 ms
. with concatenation: 49 ms
printf: 54 ms
. with concatenation: 52 ms
A nice graph of the script’s output can be found here:
http://i3x171um.com/output_benchmarks/ob.gif
So what should you choose to print your text? I found several things out writing this.
First, it should be noted that the print and echo keywords are interchangeable, performance-wise. The timings show that one is probably an alias for the other. So use whichever you feel most comfortable with.
Second, if you’ve ever wondered which was better, the definitive answer is single quotes. Single quotes are at least four times faster in any situation. Double quotes, while more convenient, do pose a debatably significant performance issue when outputting massive amounts of data.
Third, stay away from heredoc, and absolutely stay away from [s]printf. They’re slow, and the alternatives are there.
DO NOT RUN THE SCRIPT ON THE INTERNET! Run it instead from localhost. The script outputs
45 megabytes of text in an html comment at the top of the page by default. Expect the benchmark to take
45 seconds. If this is too long, you can change the amount of iterations to a lower number (the results scale accurately down to about 1,000 iterations).
Класс PHP для вывода в консоль цветного текста
Делал для себя скрипт для деплоя сайта на продакшен. Для чего нужно было выводить на экран что происходит. И чтобы было нагляднее решил выводить в цвете. Однако не смог найти что-то подходящее. Максимум библиотека выводила цветной текст, но не поддерживала отступы. Поэтому сделал свою библиотеку для этого. Возможно кому-то будет полезно. Небольшая (но функциональная) библиотека для вывода на консоль цветного текста с поддержкой отступов в таком вот виде
Установка
Для установки можно воспользоваться composer
Использование
Список всех поддерживаемых цветов. Имена колонок — цвета фона, имена строк — цвета текста.
Вывод цветного текста
Отступы
Для работы с отступами служит функция indent(значение отступа[,абсолютное значение]) — если указан второй параметр и он = true, то отступ абсолютный. Иначе отступ относительный. Для получения текущего отступа нужно вызвать функцию indent() без параметров.
вывод:
функция indent применяется к выводимой СТРОКЕ и значение будет меняться до вызова функции enter(). Т.е. вот этот код выведет строку с отступом 3
Стили
Можно указать стили. По умолчанию задан стиль ошибок «error»
вывод:
Логирование
Имеются специальные функции для контроля логирования
Значения выводятся на экран с помощью функции write() только в случае если текущий уровень логирования меньше-равен глобальноному уровню логирования.
Синтаксический сахар
Чтобы не писать color(‘red’)->bgcolor(‘green’) можно писать в коротком виде
Цвет фона можно задавать функцией без подчеркивания. Однако оно визуально отделяет цвет от префикса и, на мой взгляд, весьма удобна.
upd: раз уж мне указали на ошибку в имени функции ident вместо indent, то я её исправил чтобы не смущать тех, кто знает английский хорошо 🙂