Skip to content

Instantly share code, notes, and snippets.

@JRyven
Last active September 30, 2020 08:33
Show Gist options
  • Save JRyven/0739c68d4cdb471d414eb28832e3bd09 to your computer and use it in GitHub Desktop.
Save JRyven/0739c68d4cdb471d414eb28832e3bd09 to your computer and use it in GitHub Desktop.
OOP PHP HTML Builder
<?php
/* https://stackoverflow.com/questions/3488373/php-class-to-generate-html#answer-62349439 */
/**
* HTML - Simplest html element builder
* - @param1 Element name
* - @param2 Class name
* - @param3 ID
* - @param2 Element content
*/
class HTML{
/**
* Create a new html element
*/
private static function core($element, $content) {
return "<" . $element . ">" . $content . "</" . $element . ">";
}
/**
* Add a new param to a html element
*/
private static function addParam($elem, $param, $value) {
if (is_null($value)){return $elem;}
return implode(" $param=\"" . $value . '">', explode(">", $elem, 2));
}
/**
* Return an element with a class and an id
*/
public static function create($element, $content=null, $class=null, $id=null) {
return self::addParam(self::addParam(self::core($element, $content), "class", $class) , "id", $id);
}
}
// Examples
echo HTML::create("div", "This is it!", "redclass", "niceid");
echo PHP_EOL;
$html = new HTML();
echo HTML::create("button", "Click me!", "button", "48151");
echo PHP_EOL;
echo $html->create("p", "A paragraph");
echo PHP_EOL;
echo $html->create("h3", "Hello world!");
// OUTPUT
//<div class="redclass" id="niceid">This is wtf</div>
//<button class="button" id="48151">Click me!</button>
//<p>A paragraph</p>
//<h3>Hello world!</h3>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment