Created
April 21, 2014 17:49
-
-
Save syphoxy/11150461 to your computer and use it in GitHub Desktop.
experimental html generator from array data structure
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 | |
$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); |
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
<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