Skip to content

Instantly share code, notes, and snippets.

@syphoxy
Created April 21, 2014 17:49
Show Gist options
  • Save syphoxy/11150461 to your computer and use it in GitHub Desktop.
Save syphoxy/11150461 to your computer and use it in GitHub Desktop.
experimental html generator from array data structure
<?php
$structure = array(
'html' => array(
'children' => array(
'head' => array(
'children' => array(
'title' => array(
'children' => array(
'Hello, World'
)
)
)
),
'body' => array(
'children' => array(
'h1' => array(
'attributes' => array(
'class' => 'page-title'
),
'children' => array(
'hello, world'
)
),
'p' => array(
'children' => array(
'lorem ipsum'
)
)
)
)
)
)
);
function format($string, $options = array())
{
if (!isset($options['depth']) || is_null($options['depth'])) {
$options['depth'] = 0;
}
return str_repeat("\t", $options['depth']) . $string;
}
function startTag($tagName, $attributes = array())
{
if (!is_array($attributes) || count($attributes) == 0) {
return '<' . $tagName . '>';
}
foreach ($attributes as $attr => $value) {
$attributes_str = ' ' . $attr . '="' . $value . '"';
}
return '<' . $tagName . $attributes_str . '>';
}
function endTag($tagName)
{
return '</' . $tagName . '>';
}
function renderHtml($elements, $depth = 0)
{
$html = '';
foreach ($elements as $tagName => $spec) {
if (is_array($spec) && !isset($spec['attributes'])) {
$spec['attributes'] = array();
}
$formatOpts = array('depth' => $depth);
if (preg_match('/^[0-9]/', $tagName)) {
$html .= format($spec, $formatOpts) . PHP_EOL;
} else {
$html .= format(startTag($tagName, $spec['attributes']), $formatOpts) . PHP_EOL;
}
if (isset($spec['children']) && is_array($spec['children'])) {
$html .= renderHtml($spec['children'], $depth + 1);
}
if (!preg_match('/^[0-9]/', $tagName)) {
$html .= format(endTag($tagName), $formatOpts) . PHP_EOL;
}
}
return $html;
}
print renderHtml($structure);
<html>
<head>
<title>
Hello, World
</title>
</head>
<body>
<h1 class="page-title">
hello, world
</h1>
<p>
lorem ipsum
</p>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment