Home » Php » PHP Class to Generate HTML?

PHP Class to Generate HTML?

Posted by: admin July 12, 2020 Leave a comment

Questions:

Anyone know of any classes written for php that can clean up your code a bit?

Something like,

$htGen = new HTMLGenerator();
$htGen->newDOM('div', 'here is what goes in the div', 'optionalID', 'optionalClass');

Or does that just sound redundant?

I end up with some complex looking mish-mashes of html and php sometimes that I feel could be simplified a bit eg my latest cms bit;

foreach($details as $detail){

    $d = unserialize($detail);

    if($ad){
        print_r($d); // <-- VIEW DETAIL OBJECT IN WHOLE.
    }else{
    if($d->get_info('orphan')){
        echo '<li class="classRow orphan">' . "\n";
        echo '<div class="orphan" style="display:none">orphan</div>' . "\n";
    }else{
        echo '<li class="classRow">' . "\n";
        echo '<div class="orphan" style="display:none"></div>' . "\n";
    }

        echo '<div  class="classNumbers" id="' . $d->get_info('class ID') .  '" style="display:none"></div>' . "\n"; 
        echo '<div class="rowBG" style="overflow:hidden;width:100%">';   
            echo '<div class="startTime"></div>' . "\n";
            echo '<div class="details"><span class="classes">' . $d->get_info('class number') . '</span> - <input class="detailInput" type="text" value="' . $d->get_info('class description') . '"/><div class="editButton"><a class="editExpand">options(+)</a></div></div>' . "\n";
            echo '<div class="interval">';
            echo '<input class="intervalInput" type="text" value="' . $d->get_info('interval') . '" maxlength="5"/>';
            echo '</div>' . "\n"; 
            echo '<div class="numRiders"><input class="numRidersInput" type="text" value="' . $d->get_info('num riders') . '"/></div>' . "\n"; 
        echo '</div>'; 

        echo '<div class="classOptions">' . "\n";
            echo '<div class="selectRingMove">Move to Ring:<select id="ringSwap"><option>Select A Ring</option>' . get_ring_options() .  '</select></div>' . "\n";
            if($d->get_info('online sign up') != 'false'){
                echo '<div class="signUpContainer">Sign-Up<input type="checkbox" class="signUp" checked/></div>' . "\n";
            }else{
                echo '<div class="signUpContainer">Sign-Up<input type="checkbox" class="signUp"/></div>' . "\n";
            }
            if($d->get_info('water and drag')){
                echo '<div class="wdBoxContainer"><select id="wdDescrip"><option>WATER AND DRAG</option><option>COURSE CHANGE & WALK</option><option>OTHER</option></select><input type="checkbox" class="wdBox" checked/><input type="text" value="' . $d->get_info('water and drag') .  '" maxlength="2" class="wdInput"> min</div>' . "\n";
            }else{
                echo '<div class="wdBoxContainer"><select id="wdDescrip"><option>WATER AND DRAG</option><option>COURSE CHANGE & WALK</option><option>OTHER</option></select><input type="checkbox" class="wdBox"/><input type="text" value="20" maxlength="2" class="wdInput"> min</div>' . "\n";
            }
            if($d->get_info('ghost riders')){
                echo '<div class="ghostRidersContainer">Ghost Riders<input type="checkbox" checked class="ghostBox"><input type="text" maxlength="2" class="ghostRiderInput" value="' . $d->get_info('ghost riders') .  '"></div>' . "\n";
            }else{
                echo '<div class="ghostRidersContainer">Ghost Riders<input type="checkbox" class="ghostBox"><input type="text" maxlength="2" class="ghostRiderInput"></div>' . "\n";
            }

        echo '</div>' . "\n";

    echo '</li>' . "\n";

    if($d->get_info('water and drag')){
        echo '<li class="waterAndDragRow" style="display:block;"><span class="wdStartTime">08:33am</span> - <span class="wdEndTime">08:34am</span> <input type="text" class="wdDescription" value="' . $d->get_info('water and drag description') . '"></li>';
    }
    }
}

Or, if you know of a cleaner way to write long blocks of intermingled php vars and html… (not a big fan of EOF>>>)

Thanks in advance.

How to&Answers:

I guess it could be done with http://www.php.net/manual/en/class.domdocument.php. But that isn’t really a good way to do it.

I agree that your code code sample isn’t very clear, you could consider something like:

<ul>
<?php foreach ($items as $item): ?>
    <li>
        <?=$item['something']?>
        <?php if ($item['foo'] == 'bar'): ?>
        <ul>
            <li>bar</li>
        </ul>
        <?php else: ?>
        <ul>
            <li>foo</li>
        </ul>
        <?php endif; ?>
    </li>
<?php endforeach; ?>
<ul>

That’s a lot better imho, I use it like that in my views.

Btw, you should validate your html output. For example, a div-element isn’t allowed in a li-element.

edit:
Obviously, the following code:

<?php if ($item['foo'] == 'bar'): ?>
<ul>
    <li>bar</li>
</ul>
<?php else: ?>
<ul>
    <li>foo</li>
</ul>
<?php endif; ?>

Could be replaced by:

<ul>
    <li><?=($item['foo'] == 'bar' ? 'bar' : 'foo')?></li>
</ul>

Answer:

I’m working on a simple DSL that addresses this common task. It’s called htmlgen and it’s being hosted on Github.

I just pushed 2.x with some major improvements.

Here’s an example

use function htmlgen\html as h;

h('#wrapper',
  h('h1.title', 'Hello, World'),
  h('p',
    h('comment', 'link to project'),
    h('a', ['href'=>'https://github.com/naomik/htmlgen'], 'See htmlgen on Github')
  )
);

Here’s the output (actual output does not have whitespace)

<div id="wrapper">
  <h1 class="title">Hello, World</h1>
  <p>
    <!-- link to project -->
    <a href="https://github.com/naomik/htmlgen">See htmlgen on Github</a>
  </p>
</div>

It’s very new but at ~200 lines of source, it’s already very powerful. Fork it and make adjustments or send me a note with suggestions.

Answer:

The main idea of generating HTML is to keep HTML as is.
Just divide your script into 2 parts: prepare data part and display data part. A latter one should contain mostly HTML with some PHP control structures. Of course, there should be as less PHP code as possible. Move all unnecessary PHP code into first part.

Well to sum up all of the above:
there should be nothing to unserialize in the $details array. Have your data prepared already

<? foreach ($details as $d): ?>              
<li class="classRow orphan">
  <div class="orphan" style="display:none"><? if ($d->get_info('orphan')): ?>orphan<? endif ?></div>
   <div class="classNumbers" id="<?= $d->get_info('class ID') ?>" style="display:none"></div> 
    <div class="rowBG" style="overflow:hidden;width:100%">
     <div class="startTime"></div>
      <div class="details">
       <span class="classes"><?= $d->get_info('class number') ?></span> -
        <input class="detailInput" type="text" value="<?= $d->get_info('class description') ?>"/>
         <div class="editButton">
          <a class="editExpand">options(+)</a>
         </div>
        </div>
        <div class="interval">
         <input class="intervalInput" type="text" value="<?= $d->get_info('interval') ?>" maxlength="5"/>
        </div>
        <div class="numRiders">
         <input class="numRidersInput" type="text" value="<?= $d->get_info('num riders') ?>"/>
        </div>
       </div>
       <div class="classOptions">
       <div class="selectRingMove">Move to Ring:
        <select id="ringSwap">
         <option>Select A Ring</option>
<?= foreach (get_ring_options() as $value => $option): ?>
     <option value="<?=$value?>"><?=$option?></option>
<? endforeach ?>
         </select>
       </div>
       <div class="signUpContainer">Sign-Up
        <input type="checkbox" class="signUp" <? if (!$d->get_info('online sign up'): ?>checked<? endif ?>/>
       </div>

and so on.

The main rule should be DRY: Do not Repeat Yourself.
Do not repeat blocks of code if there is only one word difference.
But enclose that word into condition

Note that get_ring_options() was replaced with proper code.
Do not make functions that return HTML, but an array instead.

Answer:

Instead of a class, consider a library of functions to generate HTML. I didn’t use a class to make the code that you end up writing concise but expressive. With a class you must create an instance and use that variable, or make the methods static and write static references.

With this technique creating HTML for an image that is a link looks like this:

a('/example/url', img('image_url', $altText));

This is based on a script I once created. First the generic functions to generate HTML elements and attributes:

function tag($tag, $text, $attributes = array()) {
    return "<$tag" . attributesToArray($attributes) . ">$text</$tag>";
}

function minimizedTag($tag, $attributes = array()) {
    return "<$tag" . attributesToArray($attributes) . " />";
}

function attributesToArray($attributes = array()){
    $a = '';
    foreach ($attributes as $attribute => $value) {
        $a .= " $attribute='$value'";
    }
    return $a;
}

Then add functions named according to the HTML elements they create, like a() and img() to create a link and image:

function a($link, $text, $attributes = array()) {
    $a = array('href' => $link);
    foreach ($attributes as $attribute => $value) {
        $a[$attribute] = $value;
    }
    return tag('a', $text, $a);
}

function img($url, $alt = null) {
    $a = array('src' => $url);
    if (!is_null($alt)){
        if (is_array($alt)){
            $a = array_merge($a, $alt);
        } else {
            $a['alt'] = $alt;
        }
    }
    return minimizedTag('img', $a);
}

Choose the parameters to pass common attributes wisely to make the library easier to use.

Answer:

I’ll probably get downvoted for recommending short tags, but here’s what I do. I put all the <? and ?> tags at column 1 so that the code reads like a mix of PHP and HTML. No echo statements is the goal.

    foreach ($details as $detail) {
        $d = unserialize($detail);

        if ($ad) {
            print_r($d); // <-- VIEW DETAIL OBJECT IN WHOLE.
        }
        else {
            if ($d->get_info('orphan')) {
?>              <li class="classRow orphan">
                  <div class="orphan" style="display:none">orphan</div>
<?          }
            else {
?>              <li class="classRow">
                  <div class="orphan" style="display:none"></div>
<?          }

?>          <div class="classNumbers" id="<?= $d->get_info('class ID') ?>"
                 style="display:none"></div> 
            <div class="rowBG" style="overflow:hidden;width:100%">
              <div class="startTime"></div>
              <div class="details">
                <span class="classes"><?= $d->get_info('class number') ?></span> -
                <input class="detailInput" type="text" value="<?= $d->get_info('class description') ?>"/>
                <div class="editButton">
                  <a class="editExpand">options(+)</a>
                </div>
              </div>
              <div class="interval">
                <input class="intervalInput" type="text" value="<?= $d->get_info('interval') ?>" maxlength="5"/>
              </div>
              <div class="numRiders">
                <input class="numRidersInput" type="text" value="<?= $d->get_info('num riders') ?>"/>
              </div>
            </div>

            <div class="classOptions">
              <div class="selectRingMove">
                Move to Ring:
                <select id="ringSwap">
                  <option>Select A Ring</option>
                  <?= get_ring_options() ?>
                </select>
              </div>

<?            if ($d->get_info('online sign up') != 'false') {
?>                <div class="signUpContainer">
                    Sign-Up
                    <input type="checkbox" class="signUp" checked/>
                  </div>
<?            }
              else {
?>                <div class="signUpContainer">
                    Sign-Up
                    <input type="checkbox" class="signUp"/>
                  </div>
<?            }

              if ($d->get_info('water and drag')) {
?>                <div class="wdBoxContainer">
                    <select id="wdDescrip">
                      <option>WATER AND DRAG</option>
                      <option>COURSE CHANGE &amp; WALK</option>
                      <option>OTHER</option>
                    </select>

                    <input type="checkbox" class="wdBox" checked/>
                    <input type="text" value="<?= $d->get_info('water and drag') ?>" maxlength="2" class="wdInput"> min
                  </div>
<?            }
              else {
?>                <div class="wdBoxContainer">
                    <select id="wdDescrip">
                      <option>WATER AND DRAG</option>
                      <option>COURSE CHANGE &amp; WALK</option>
                      <option>OTHER</option>
                    </select>

                    <input type="checkbox" class="wdBox"/>
                    <input type="text" value="20" maxlength="2" class="wdInput"> min
                  </div>
<?            }

              if ($d->get_info('ghost riders')) {
?>                <div class="ghostRidersContainer">
                    Ghost Riders
                    <input type="checkbox" checked class="ghostBox">
                    <input type="text" maxlength="2" class="ghostRiderInput" value="<?= $d->get_info('ghost riders') ?>">
                  </div>
<?            }
              else {
?>                <div class="ghostRidersContainer">
                    Ghost Riders
                    <input type="checkbox" class="ghostBox">
                    <input type="text" maxlength="2" class="ghostRiderInput">
                  </div>
<?            }
?>          </div>
            </li>

<?          if ($d->get_info('water and drag')) {
?>              <li class="waterAndDragRow" style="display:block;">
                  <span class="wdStartTime">08:33am</span> -
                  <span class="wdEndTime">08:34am</span>
                  <input type="text" class="wdDescription" value="<?= $d->get_info('water and drag description') ?>">
                </li>
<?          }
        }
    }

Answer:

In regards to PHP classes to generate HTML, you could use http://api20.cakephp.org/class/html-helper an object from the cake PHP framework.
The others have already addressed your not so clean code.

It uses this format: div( $class = NULL, $text = NULL, $options = array ( ) )

Answer:

why not create your own clases?? or at least some functions… and i saw that you use alot of IF, you may clean it using vairables like when you have

if($d->get_info('ghost riders')){
            echo '<div class="ghostRidersContainer">Ghost Riders<input type="checkbox" checked class="ghostBox"><input type="text" maxlength="2" class="ghostRiderInput" value="' . $d->get_info('ghost riders') .  '"></div>' . "\n";
        }else{
            echo '<div class="ghostRidersContainer">Ghost Riders<input type="checkbox" class="ghostBox"><input type="text" maxlength="2" class="ghostRiderInput"></div>' . "\n";
        }

you could write:

$check = ($d->get_info('ghost riders'))?"checked":"";
echo '<div class="ghostRidersContainer">Ghost Riders<input type="checkbox" '.$check.' class="ghostBox"><input type="text" maxlength="2" class="ghostRiderInput" value="' . $d->get_info('ghost riders') .  '"></div>' . "\n";

it will look cleaner 🙂 I’ve created a Form class that helps me when i have to create forms and the code is more legible

Answer:

Something like this?

<?php

    $html->tag('doctype')->alone('html')->tag();
    $html->tag('html')->lang('en');

        $html->tag('head');
            $html->tag('meta')->charset('utf-8')->tag();
            $html->tag('meta')->httpequiv('X-UA-Compatible')->content('IE=edge')->tag();
            $html->tag('meta')->name('viewport')->content('width=device-width, initial-scale=1')->tag();
            $html->tag('meta')->name('description')->content('Brosta Tools')->tag();
            $html->tag('meta')->name('author')->content('Brosta')->tag();
            $html->tag('title')->text('Brosta Tools')->tag();
            $html->tag('link')->href('assets/plugins/bootstrap/css/bootstrap.min.css')->rel('stylesheet')->tag();
            $html->tag('link')->href('assets/plugins/bootstrap/css/simple-sidebar.css')->rel('stylesheet')->tag();
            $html->tag('link')->href('assets/plugins/prism/css/prism.css')->rel('stylesheet')->tag();
            $html->tag('link')->href('assets/plugins/normalize/css/normalize.css')->rel('stylesheet')->tag();
            $html->tag('link')->href('assets/plugins/brosta/css/brosta.css')->rel('stylesheet')->tag();

            $html->tag('script')->src('assets/plugins/bootstrap/js/jquery.js')->type('text/javascript')->tag();
            $html->tag('script')->src('assets/plugins/bootstrap/js/bootstrap.min.js')->type('text/javascript')->tag();
            $html->tag('script')->src('assets/plugins/prism/js/prism.js')->type('text/javascript')->tag();
            $html->tag('script')->type('text/javascript')->text('$("#menu-toggle").click(function(e) {e.preventDefault(); $("#wrapper").toggleClass("toggled"); });')->tag();
            $html->tag('script')->type('text/javascript')->text('
                window.onload = function () { 
                    var x = document.getElementsByClassName("token");
                    var i;
                    for (i = 0; i < x.length; i++) {
                        var variable = x[i].getAttribute("class").replace("token ", "");
                        var text = x[i].innerText.trim().replace("$", "");
                        if(!/[^a-zA-Z0-9]/.test(text) || text.indexOf("_") >= 0) {
                            x[i].className +=" " + variable + "-" + text;
                        }
                    }
                }
            ')->tag();
        $html->tag();

        $html->tag('body')->class('brosta');

            $html->include('snippets.brosta.navbar');

            $html->tag('div')->class('container-fluid brosta');
                $html->tag('div')->id('wrapper');
                    $html->tag('div')->id('sidebar-wrapper');
                        $html->tag('ul')->class('sidebar-nav');

                            $data = [
                                ['link' => '/Instalation', 'text' => 'Instalation'],
                                ['link' => '/Html', 'text' => 'Html']
                            ];

                            foreach($data as $link)
                            {
                                $html->tag('li');
                                    $html->tag('a')->href($link['link'])->text($link['text'])->tag();
                                $html->tag();
                            }

                        $html->tag();
                    $html->tag();
                    $html->tag('div')->id('page-content-wrapper');
                        $html->tag('div')->class('row');
                            $html->tag('div')->class('col-lg-12');
                                $html->tag('div')->class('panel panel-default');
                                    $html->tag('div')->class('panel-heading clearfix')->text('Without Time')->tag();
                                    $html->tag('div')->class('panel-body');
                                        $html->tag('p')->text('Make a file in your root public server. Ex: <code class="language-php">C:\xampp\htdocs\index.php</code>')->tag();
                                        $html->tag('pre')->class('language-php');
                                            $html->tag('code')->class('language-php')->text($html->specialChars('views/content.php'))->tag();
                                        $html->tag();
                                    $html->tag();
                                $html->tag();
                            $html->tag();
                        $html->tag();
                    $html->tag();
                $html->tag();
            $html->tag();
        $html->tag();
    $html->tag();

echo $html->get();

Answer:

This is a bit late, but I’ve recently written an object-oriented HTML generator for PHP. It supports nesting.

As an example, this…

$h = new \HTML;
echo $h::div(
    'class', 'my-class', 
    'id', 'my-id',
    $h::p(
        'class', 'paragraph',
        'It was a dark and stormy night, at least according to the beginning of the book.'
    )
);

…will create this markup (without spaces between the tags)…

<div class="my-class" id="my-id">
    <p class="paragraph">It was a dark and stormy night, at least according to the book.</p>
</div>

Hope you find it useful!

Answer:

studiowbe/html is the right package for me. It has a sound API, with chaining, and it is enabled on Composer.

$link = new Studiow\HTML\Element("a");
$link->setInnerHTML("Documents")
        ->setAttribute("href", "/documents")
        ->addClass("button")
        ->addClass("button-documents")
        ->setAttribute('title', "Go to documents");
echo (string) $link; // Outputs <a href="/documents" class="button button-documents" title="Go to documents">Documents</a>

Answer:

Do not mix html and php code!
I would do this: https://github.com/HanKruma/Tag-Generator

“Tag gen”

<?php

namespace Main;

/**
 * Description of Tag
 *
 * @author HanKrum
 */
class Tag {


    private $_tags = ['doctype', 'br', 'hr', 'input', 'meta', 'base', 'basefont', 'img', 'source'];

    public function __call($name, $arguments) {
        $attr = null;
        $text = null;
        if (\in_array($name, $this->_tags)) {
            $name = $name == $this->_tags[0] ? '!' . $name . ' html' : $name;
            foreach ($arguments as $v) {
                $attr .= ' ' . $v;
            }
            return '<' . $name . $attr . '>' . "\n";
        }
        $br = 0;
        $count = \count($arguments);
        foreach ($arguments as $v) {
            $br ++;
            if ($br == $count) {
                $text = $v;
            } else {
                if (!$v) {
                    $space = null;
                } else {
                    $space = ' ';
                }
                $attr .= $space . $v;
            }
        }
        return '<' . $name . $attr . '>' . $text . '</' . $name . '>' . "\n";
    }

}

And use this that:

<?php
$ob = new \Main\Tag();
echo $ob->input('class="doc"', 'placeholder="Title"', 'name="title"');
echo $ob->span(null, 'Text');
exit($ob->button('class="submit"', 'Write');

Answer:

For those looking for the simple start. This is enough to generate a wide variety of elements.

This will create any kind of element, give some content, a class, and an id.

You will have to handle special cases yourself, if you are using it in your app.

<?php
/**
 * 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>
.redclass {background: red}
<div class="redclass" id="niceid">This is it!</div>
<button class="button" id="48151">Click me!</button>
<p>A paragraph</p>
<h3>Hello world!</h3>