Last active
March 6, 2017 22:04
-
-
Save garvin/66cb2f78a67d188d5f884dcf6730b1ce to your computer and use it in GitHub Desktop.
Quick & dirty output-an[-associative?]-array as a <table> function
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
/** | |
* Given an array, return its contents as a <table> | |
* | |
* @param mixed $r | |
* @return string If $r is an array, returns HTML of a <table> representing its contents. | |
* If $r is a string, returns that string with HTML entities converted. | |
* If $r is not a string or array, returns var_export($r, true) with HTML entities converted. | |
*/ | |
function output_array_as_table($r) { | |
// function for doing some entitifying of strings | |
// probably should be a callback | |
$utf8_entities = function($string, $double_encode = true) { | |
return htmlentities((string) $string, ENT_QUOTES, "UTF-8", $double_encode); | |
}; | |
if (is_array($r)) { | |
$out = " | |
<table><tbody>"; | |
if (empty($r)) { | |
$out .= " | |
<tr><td colspan='2'>[empty array]</td></tr>"; | |
} | |
else { | |
foreach ($r as $key => $val) { | |
$out .= sprintf( | |
"<tr> | |
<th>%s</th> | |
<td>%s</td> | |
</tr>", | |
$utf8_entities($key), | |
output_array_as_table($val) | |
); | |
} | |
} | |
$out .= " | |
</tbody></table>"; | |
return $out; | |
} | |
if (is_string($r)) { | |
return $utf8_entities($r); | |
} | |
// not a string or array | |
return $utf8_entities(var_export($r, true)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment