<?php
$var = array('Oh', 'yes', 'baby', '!!');
echo Console::log('un_nombre', $var);
Last active
April 7, 2023 17:51
-
-
Save demonio/00495c0bbd479ed89adc to your computer and use it in GitHub Desktop.
Clase para imprimir variables PHP en la consola del navegador
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Clase para imprimir variables PHP en la consola del navegador. | |
* | |
* Esta clase ha sido creada a partir de esta otra: | |
* http://www.codeforest.net/debugging-php-in-browsers-javascript-console | |
*/ | |
class Console | |
{ | |
/** | |
* @param string $name Nombre único para poder ejecutar esto varias veces en el mismo documento | |
* @param mixed $var Una variable cadena, objeto, matriz o lo que sea | |
* @param string $type (debug|info|warn|error) | |
* @return html | |
*/ | |
public static function log($name, $var, $type='debug') | |
{ | |
$name = preg_replace('/[^A-Z|0-9]/i', '_', $name); | |
$types = array('debug', 'info', 'warn', 'error'); | |
if ( ! in_array($type, $types) ) $type = 'debug'; | |
$s = '<script>' . PHP_EOL; | |
if ( is_object($var) or is_array($var) ) | |
{ | |
$object = json_encode($var); | |
$object = str_replace("'", "\'", $object); | |
$s .= "var object$name = '$object';" . PHP_EOL; | |
$s .= "var val$name = eval('('+object$name+')');" . PHP_EOL; | |
$s .= "console.$type(val$name);" . PHP_EOL; | |
} | |
else | |
{ | |
$var = str_replace('"', '\\"', $var); | |
$s .= "console.$type($var);" . PHP_EOL; | |
} | |
$s .= '</script>' . PHP_EOL; | |
return $s; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Gracias, me ha sido de gran ayuda.
Solo apuntar que la salida no la hace por la consola, sino por el response de php en la pestaña network.
Saludos