Friday, August 3, 2012

I thought its about time I started a blog.  The main reason is I need somewhere to keep track of my code notes, and typing it out helps me remember better.  If you do happen by,  feel free to use any code you find.

I have been scripting a lot of PHP and HTML lately and have been wanting the Object Oriented Functions within PHP to be available for the HTML I have been writing so I came up with this.


<?php

/**
 * Description of HTML
 *  -- OO-HTML --
 * @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', '1');
 * echo $mydiv->HTML();
 *
 * <div name='mydiv'>
 * Hello World
 * </div>
 *
 *
 * I added some functions to make it a bit more like actionscript but you can also manipulate the tag arrays directly.
 *
 */
class HTML
{  
    public $cmd = "";
    public $vals = array();
    public $children = array();
   
    public function __construct($cmd)
    {
        $this->cmd = $cmd;
    }
   
    public function HTML()
    {
        $r = "";
       
        //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
        $r = "<".$this->cmd.$val.">\n$child</".$this->cmd.">";
        return $r;
    }
   
    public function addChild($child, $num)
    {
        $this->children[$num] = $child;
    }
   
    public function removeChild($num)
    {
        unset($this->children[$num]);
    }
   
    public function addValue($cmd, $val)
    {
        $this->vals[$cmd] = $val;
    }
   
    public function removeValue($cmd)
    {
        unset($this->vals[$cmd]);
    }
}

?>

No comments:

Post a Comment