createElement () method in PHP

5

In javascript, I can do:

var span = document.createElement('span');
span.innerHTML = 'foo';
span.className = 'bar';

Is there something similar so that I can create a ElementNode in PHP, at least with the basic attributes (name, class, id, etc.)? Example:

$span = HTML::create('span');
$span->innerHtml = 'foo';
$span->className = 'bar';

echo $span->toString();

And the result will be:

<span class="bar">foo</span>
    
asked by anonymous 23.01.2014 / 00:23

3 answers

2

For the creation of full XML (or XHTML) the best solution is the DOMDocument API, as mentioned in the other answers.

However, if your goal is simply to create an HTML tag in a simple way, I believe there are simpler forms.

Simple solution: a function

In a few minutes, I wrote the following function:

function createElement($tag_name, array $attributes = array(), $content = null) {

    $attr_text = '';
    foreach ($attributes as $name => $value) {
        $attr_text .= ' ' . $name . '="' . $value . '"';
    }
    return '<' . $tag_name . $attr_text . 
            (is_null($content) ? '/>' : '>' . $content . '</' . $tag_name . '>');

}

Examples of use:

createElement('br');
createElement('button', array(), '');
createElement('input', array('type' => 'submit', 'id' => 'enviar'));
createElement('textarea', array('id' => 'caixa-de-texto'), 'Contéudo da textarea');

Return calls above, in order:

<br/>
<button></button>
<input type="submit" id="enviar"/>
<textarea id="caixa-de-texto">Contéudo da textarea</textarea>

See the working example at link .

If you find a different case, you can simply fine-tune the function.

A slightly more complete solution: a class

I found in this link a class created exactly with the same purpose of this question. The implementation is not complicated and allows an object-oriented approach.

Follow the code:

/* creates an html element, like in js */
class html_element
{
    /* vars */
    var $type;
    var $attributes;
    var $self_closers;

    /* constructor */
    function html_element($type,$self_closers = array('input','img','hr','br','meta','link'))
    {
        $this->type = strtolower($type);
        $this->self_closers = $self_closers;
    }

    /* get */
    function get($attribute)
    {
        return $this->attributes[$attribute];
    }

    /* set -- array or key,value */
    function set($attribute,$value = '')
    {
        if(!is_array($attribute))
        {
            $this->attributes[$attribute] = $value;
        }
        else
        {
            $this->attributes = array_merge($this->attributes,$attribute);
        }
    }

    /* remove an attribute */
    function remove($att)
    {
        if(isset($this->attributes[$att]))
        {
            unset($this->attributes[$att]);
        }
    }

    /* clear */
    function clear()
    {
        $this->attributes = array();
    }

    /* inject */
    function inject($object)
    {
        if(@get_class($object) == __class__)
        {
            $this->attributes['text'].= $object->build();
        }
    }

    /* build */
    function build()
    {
        //start
        $build = '<'.$this->type;

        //add attributes
        if(count($this->attributes))
        {
            foreach($this->attributes as $key=>$value)
            {
                if($key != 'text') { $build.= ' '.$key.'="'.$value.'"'; }
            }
        }

        //closing
        if(!in_array($this->type,$this->self_closers))
        {
            $build.= '>'.$this->attributes['text'].'</'.$this->type.'>';
        }
        else
        {
            $build.= ' />';
        }

        //return it
        return $build;
    }

    /* spit it out */
    function output()
    {
        echo $this->build();
    }
}

Example usage:

$my_anchor = new html_element('a');
$my_anchor->set('href','http://davidwalsh.name');
$my_anchor->set('title','David Walsh Blog');
$my_anchor->set('text','Click here!');
$my_anchor->output();

This generates output:

<a href="http://davidwalsh.name" title="David Walsh Blog">Click here!</a>

This basic implementation does almost the same thing as the function presented in the previous topic, but it allows you to easily extend the functionality.

Reading the comments from the site where I found the class, you can find several improvements to the class, for example the possibility to include child elements or a function to set CSS styles individually.

I would personally include setters to receive associative array of both attributes and styles.

Complete solution: a library

After looking at all the comments from the previous link, I saw that someone got the same idea and wrote a small library called phpcreatehtml to make HTML creation easier.

See an example usage:

$php=create('html',
  $head = head(title('My Page')),
  body(
    $header = div('class','header'),
    $body = div('class','main'),
    $footer = div('class','footer')
  )
);
$body->append(h1('This example'));
$body->append(
  h2('is more convenient!'),
  div('class','main')->append(
    p('It uses less confusing technics to code.')
  )
);
echo $php;

This generates the following output:

<html>
  <head>
    <title>My Page</title>
  </head>
  <body>
    <div class="header"></div>
    <div class="main">
      <h1>This example</h1>
      <h2>is more convenient!</h2>
      <div class="main">
        <p>It uses less confusing technics to code.</p>
      </div>
    </div>
    <div class="footer"></div>
  </body>
</html>

Conclusions

I do not think you're going to need to "reinvent the wheel again," because a lot of people have already done it.

Just set the level of complexity you'll need. If it's just to print simple elements, I'd go for the simplest solution (function) and so on.

    
23.01.2014 / 12:38
5

Directly there is no function for this, the most similar thing is the DOMDocument::createElement , but is XML oriented. However, it is relatively simple to implement a function of its own.

Here's a pretty easy to understand, coming from this site .:

class html_element
{
    /* vars */
    var $type;
    var $attributes;
    var $self_closers;

    /* constructor */
    function html_element($type,$self_closers = array('input','img','hr','br','meta','link'))
    {
        $this->type = strtolower($type);
        $this->self_closers = $self_closers;
    }

    /* get */
    function get($attribute)
    {
        return $this->attributes[$attribute];
    }

    /* set -- array or key,value */
    function set($attribute,$value = '')
    {
        if(!is_array($attribute))
        {
            $this->attributes[$attribute] = $value;
        }
        else
        {
            $this->attributes = array_merge($this->attributes,$attribute);
        }
    }

    /* remove an attribute */
    function remove($att)
    {
        if(isset($this->attributes[$att]))
        {
            unset($this->attributes[$att]);
        }
    }

    /* clear */
    function clear()
    {
        $this->attributes = array();
    }

    /* inject */
    function inject($object)
    {
        if(@get_class($object) == __class__)
        {
            $this->attributes['text'].= $object->build();
        }
    }

    /* build */
    function build()
    {
        //start
        $build = '<'.$this->type;

        //add attributes
        if(count($this->attributes))
        {
            foreach($this->attributes as $key=>$value)
            {
                if($key != 'text') { $build.= ' '.$key.'="'.$value.'"'; }
            }
        }

        //closing
        if(!in_array($this->type,$this->self_closers))
        {
            $build.= '>'.$this->attributes['text'].'</'.$this->type.'>';
        }
        else
        {
            $build.= ' />';
        }

        //return it
        return $build;
    }

    /* spit it out */
    function output()
    {
        echo $this->build();
    }
}

Example usage:

$my_anchor = new html_element('a');
$my_anchor->set('href','http://davidwalsh.name');
$my_anchor->set('title','David Walsh Blog');
$my_anchor->set('text','Click here!');
$my_anchor->output();
//<a href="http://davidwalsh.name" title="David Walsh Blog">Click here!</a>

Author: David Walsh

Here is the example adapted to the parameters given in the question:

$span = new html_element('span');
$span->set('text', 'foo');
$span->set('class', 'bar');
$span->output();
//<span class="bar">foo</span>
    
23.01.2014 / 00:32
3

There is a DOMDocument class in PHP that allows you to do what you want.

Example using createElement :

<?php
$domDocumento = new DOMDocument('1.0', "UTF-8");
$domElemento = $domDocument->createElement('field','conteudo');
$domAtributo = $domDocument->createAttribute('name');

// Setando valor para o atributo
$domAtributo->value = 'valor';

// Inserindo atributo no elemento
$domElemento->appendChild($domAtributo);

// Inserindo elemento no documento
$domDocumento->appendChild($domElemento);
?>
    
23.01.2014 / 00:29