Метод createElement() в PHP


В javascript, я могу сделать:

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

Есть ли что-то подобное, чтобы можно было создать ElementNode в PHP, по крайней мере, с основных атрибутов (name, class, id, etc.)? Пример:

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

echo $span->toString();

результат:

<span class="bar">foo</span>
Author: Calebe Oliveira, 2014-01-22

3 answers

Для создания XML (или XHTML) полный лучшим решением является API DOMDocument, как уже упоминалось в других ответов.

Однако, если ваша цель-просто создать Тег HTML-либо простым способом, я считаю, что есть более простые формы.

Простое Решение: функция

Несколько минут rascunhei следующую функцию:

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 . '>');

}

Пример использования:

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

Возвращение звонков выше, по порядку:

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

Посмотрите пример функциональный http://codepad.org/a4qLJZq8.

, Если найти какой-то другой случай, вы можете просто идти, совершенствуя функции.

Решение немного более полным: класс

Нашел link класса, который создается именно с такой же целью на этот вопрос. Реализация не сложная и позволяет использовать объектно-ориентированный подход.

Следующий код:

/* 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();
    }
}

Пример использования:

$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>

Эта реализация базовой делает почти то же самое, функции, показанное в предыдущей теме, но позволяет легко расширить функциональные возможности.

, Читая отзывы, сайт, где я нашел класс можно найти множество сообщений улучшений для класса, например возможность включать дочерние элементы, или функции, чтобы установить стили CSS по отдельности.

Лично я включил setter, чтобы получить массив ассоциативный столько атрибутов, сколько стилей.

Комплексное Решение: в библиотеке

Далее смотреть все отзывы по ссылке выше, я увидела, что кто-то взял ту же идею и написал небольшую библиотеку вызова phpcreatehtml для создания HTML проще.

Пример использования:

$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;

Это генерирует следующий вывод:

<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>

Выводам

Я Думаю, что вам не нужно будет "изобретать колесо еще раз", потому что несколько человек уже сделали.

Установите уровень сложности, который вам понадобится. Если только печатать элементы простые, я бы за самое простое решение (функция) и так далее.

 2
Author: utluiz, 2014-01-23 11:38:41

Непосредственно не есть функция для этого, самое похожее-это DOMDocument::createElement, но она ориентирована на XML. Тем не менее, это относительно просто реализовать собственную функцию для этого.

Се, ну, просто, чтобы понять, пришествие этого сайта.:

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();
    }
}

Пример использования:

$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>

Автор: David Walsh

Следующий пример адаптирован профессионалы параметров, данных на вопрос: "

$span = new html_element('span');
$span->set('text', 'foo');
$span->set('class', 'bar');
$span->output();
//<span class="bar">foo</span>
 5
Author: Bacco, 2014-01-23 00:16:12

Существует в PHP класс DOMDocument, которая позволяет осуществить требуемое.

Пример использования метода 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);
?>
 3
Author: Kenny Rafael, 2014-01-23 11:15:43