Как я могу написать на консоль в PHP? - PullRequest
274 голосов
/ 01 декабря 2010

Можно ли написать строку или войти в консоль?

Что я имею в виду

Так же, как в jsp, если мы напечатаем что-то вроде system.out.println("some"), оно будет там на консоли, а не встр.

Ответы [ 23 ]

1 голос
/ 04 мая 2016

Любой из этих двух работает:

<?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>");
?>
0 голосов
/ 26 июля 2018

Вот удобная функция. Он очень прост в использовании, позволяет передавать любое количество аргументов любого типа и отображает содержимое объекта в окне консоли браузера, как если бы вы вызывали console.log из JavaScript - но из PHP

Обратите внимание, что вы также можете использовать теги, передав «TAG-YourTag», и он будет применяться до тех пор, пока не будет прочитан другой тег, например, «TAG-YourNextTag»

/*
*   Brief:          Print to console.log() from PHP
*   Description:    Print as many strings,arrays, objects, and other data types to console.log from PHP.
*                   To use, just call consoleLog($data1, $data2, ... $dataN) and each dataI will be sent to console.log - note that
*                   you can pass as many data as you want an this will still work.
*
*                   This is very powerful as it shows the entire contents of objects and arrays that can be read inside of the browser console log.
*                   
*                   A tag can be set by passing a string that has the prefix TAG- as one of the arguments. Everytime a string with the TAG- prefix is
*                   detected, the tag is updated. This allows you to pass a tag that is applied to all data until it reaches another tag, which can then
*                   be applied to all data after it.
*
*                   Example:
*                   consoleLog('TAG-FirstTag',$data,$data2,'TAG-SecTag,$data3); 
*                   Result:
*                       FirstTag '...data...'
*                       FirstTag '...data2...'
*                       SecTag   '...data3...' 
*/
function consoleLog(){
    if(func_num_args() == 0){
        return;
    }

    $tag = '';
    for ($i = 0; $i < func_num_args(); $i++) {
        $arg = func_get_arg($i);
        if(!empty($arg)){       
            if(is_string($arg)&& strtolower(substr($arg,0,4)) === 'tag-'){
                $tag = substr($arg,4);
            }else{      
                $arg = json_encode($arg, JSON_HEX_TAG | JSON_HEX_AMP );
                echo "<script>console.log('".$tag." ".$arg."');</script>";
            }       
        }
    }
}

ПРИМЕЧАНИЕ: func_num_args () и func_num_args () являются функциями php для чтения динамического числа входных аргументов и позволяют этой функции иметь бесконечно много запросов console.log от одного вызов функции

0 голосов
/ 11 июня 2014
function console_log( $data ) {
    $bt = debug_backtrace();
    $caller = array_shift($bt);

    if ( is_array( $data ) )
        error_log( end(split('/',$caller['file'])) . ':' . $caller['line'] . ' => ' . implode( ',', $data) );
    else
        error_log( end(split('/',$caller['file'])) . ':' . $caller['line'] . ' => ' . $data );

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...