Tuesday, September 11, 2012

Update to my Object Oriented HTML class


I removed most of the Actionscript like functions because it can not be changed after the server has sent it to the client.  I am testing some HTML class extensions and will post them soon.


<?php

/**
 * Description of HTML
 *  -- OO-HTML 1.1 --
 * - Removed some methods that it didnt make sense to have.
 * - Removed array key name requirement on addChild
 *
 * @author Joseph Tveter
 *
 * Class to allow HTML to be eaisly written in native php
 * It will also work for building xml
 *
 * The $cmd string is the tag command such as a,div,html
 *
 * The $vals array holds a list of value commands for the html tag
 *
 * The $children array holds a list of children of the tag.  They will be placed in decending order, so a tag at [1] will come before a tag at [2]
 *
 * To print the string call HTML();
 * example:
 *
 * $mydiv = new HTML('div');
 * $mydiv->addValue('name', 'mydiv');
 * $mydiv->addChild('Hello World');
 * echo $mydiv->HTML();
 *
 * This will print.
 * --------------------
 * <div name='mydiv'>
 * Hello World
 * </div>
 * ----------------------
 *
 */
class HTML
{  
    public $cmd = "";
    public $vals = array();
    public $children = array();
   
    public function __construct($cmd)
    {
        $this->cmd = $cmd;
    }
   
    public function HTML()
    {
        $r = "";
        $s = false;
        $singleArr = array('input', 'hr', 'meta', 'link');
       
        foreach($singleArr as $i)
        {
            if($this->cmd == $i)
            {
                $s = true;
            }
        }
       
        //values
        $val = "";
        foreach($this->vals as $k => $v)
        {
            $val = $val." ".$k."=\"$v\"";
        }
       
        //Children
        $child = "";
        foreach($this->children as $v)
        {
            $child = $child.$v."\n";
        }
       
        //Build and return the HTML string
        if($s == false)
        {
            $r = "<".$this->cmd.$val.">\n$child</".$this->cmd.">";
        }
        else
        {
            $r = "<".$this->cmd.$val."/>\n".$child;
        }
        return $r;
    }
   
    public function addChild($child)
    {
        $this->children[count($this->children) + 1] = $child;
    }
   
    public function addValue($cmd, $val)
    {
        $this->vals[$cmd] = $val;
    }
}

?>

No comments:

Post a Comment