Skip to content

Instantly share code, notes, and snippets.

@ApoGouv
Last active March 20, 2024 10:09
Show Gist options
  • Save ApoGouv/7814151f2f6b97bde6d7d9c7789e460a to your computer and use it in GitHub Desktop.
Save ApoGouv/7814151f2f6b97bde6d7d9c7789e460a to your computer and use it in GitHub Desktop.
PHP - Pretty print data for debugging.

Print readable (copy/paste ready) code

echo '<pre>' . var_export($data, true) . '</pre>';

OR

with syntax highlighting

highlight_string("<?php\n\$data =\n" . var_export($data, true) . ";\n");

Log data to file in a readable format

// Log debug data by date and time on a file.
error_log( '[' . date('Y-m-d H:i:s') . '] $debug_array: ' . print_r($debug_array, true) . PHP_EOL, 3, '/PATH_TO_LOG/debug_data.log');

In case we need to persist the logs, it is helpfull to add date to the log file name for easier management of logs.

// Log debug data by time on log files by date.
error_log( '[' . date('H:i:s') . '] $debug_array: ' . print_r($debug_array, true) . PHP_EOL, 3, '/PATH_TO_LOG/debug_data_' . date('d_m_Y') . '.log');

Print var to (js) console

function debugToConsole($data) { 
    echo "<script>console.log(".json_encode($data).")</script>";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment