Skip to content

Instantly share code, notes, and snippets.

@amirkdv
Created Apr 24, 2014
Embed
What would you like to do?
Convert arbitrary data objects to HTML tables
<?php
/**
* Render arbitrary nested PHP variables into readable HTML. toHtmlTable()
* accepts an arbitrary variable of any of the following forms:
* - objects are first cast to associative arrays and then rendered as such.
* - arrays are rendered as a table with two columns: keys and values.
* - primitive data types are cast to strings
*
* Example usage:
* $data = json_decode(file_get_contents('/foo/bar.json'));
* $html = toHtml($data);
* file_put_contents('/foo/bar.html', $html);
*
* @param mixed $data
* @return string
* An HTML document
*/
function toHtml($data){
$body = toHtmlTable($data);
$html = <<<EOF
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style type="text/css">
#container { width: 80%; margin: auto; background: #EEE; }
#container * { font-family: monospace; }
td.key { color: #555; }
button.collapse { color: #00F; font-size: 0.7em; background:none; padding: 0; border: none; }
table { border-bottom: 2px solid #222; padding-bottom: 1em; }
td { vertical-align: top; }
</style>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js' type='text/javascript'></script>
<script type="text/javascript">
$(document).ready(function(){
$('button.collapse').mouseup(tableToggle);
});
var tableToggle = function(event){
if (event.which !== 1) {
return;
}
event.stopPropagation();
event.preventDefault();
$(event.target).parent().next('.data').toggle();
$(event.target).siblings('button.collapse').show();
$(event.target).hide();
};
</script>
</head>
<body> <div id="container">
$body
</div></body>
</html>
EOF;
return $html;
}
/**
* @param mixed $data
* @param int $depth
* depth after wich inner tables will be collapsed
* @return string
* An HTML <table> tag containing all the data in $data
*/
function toHtmlTable($data, $depth = 0){
$hide = ( $depth > 3 );
switch (gettype($data)){
case 'object':
$data = (array)$data; // fall through
case 'array':
$collapse = sprintf('<button class="collapse" %s>[-]</button>' .
'<button class="collapse" %s>[+]</button>',
$hide ? 'style = "display: none"' : '',
$hide ? '' : 'style = "display: none"');
$body = '';
foreach ($data as $key => $value){
$body .= sprintf("<tr>\n<td class='key'>%s</td>\n<td>\n%s\n</td>\n</tr>\n",
$key,
toHTMLTable($value, $depth + 1));
}
$html = sprintf("<div>%s</div>\n<table class='data' %s><tbody>\n%s</tbody></table>\n",
$collapse,
$hide ? 'style = "display: none"' : '',
$body);
break;
default:
$html = "<table>$data</table>";
break;
}
return $html;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment