Php добавление html элемента

How to Generate HTML elements using PHP

Recently I faced a situation in which I needed to generate HTML documents using core PHP. When I searched php.net I came out with very interesting PHP utility to generate XML/HTML documents and tags. This utility is DOMDocument class. DOMDocument provide us a number of functions to create new XML/HTML tags and insert those tags into the DOM. See the live demo.

Live demo Download Script

Creating new DOM document

 
$dom = new DOMDocument('1.0');//Create new document with specified version number
echo $dom->saveHTML(); //Outputs the generated source code
?>

Adding a new HTML element in DOM document

 
$css_text = 'p';
$style = $dom->createElement('style', $css_text);//Create new tag with the css tags
$dom->appendChild($style);//Add the style tag to document
//The above code will output:
style>
pcolor:#ff00ff;>
/style>
?>

If we want to create a closing element like then the createElement function will take second parameter as the contained text or value. As in the above example the element is provided the CSS text to be contained. If we want to generate the open tag like
, we need to skip the secong parameter in the createElement function.

Adding a empty HTML element in DOM document

 
$br = $dom->createElement('br');//Create new
tag

$dom->appendChild($br);//Add the
tag to document

?>

Adding a attributes to HTML elements

The html elements take various attributes. Adding attributes to the elements is very simple and is done using createAttribute function.

 
$css_text = 'p';
$style = $dom->createElement('style', $css_text);//Create new tag with the css tags
$domAttribute = $dom->createAttribute('type');//Create the new attribute 'type'
$domAttribute->value = 'text/css';//Add value to attribute
$style->appendChild($domAttribute);//Add the attribute to the style tag
$dom->appendChild($style);//Add the style tag to document
//The above code will output:
style type="text/css">
pcolor:#ff00ff;>
/style>
?>
 
$p_text = 'This is a paragraph.';
$p = $dom->createElement('p', $p_text);//Create new

tag with text
$domAttribute = $dom->createAttribute('id');//Create the new attribute 'id'
$domAttribute->value = 'description';//Add value to attribute
$p->appendChild($domAttribute);//Add the attribute to the p tag
$dom->appendChild($p);//Add the p tag to document
//The above code will output:
p id="description">
This is a paragraph.
/p>
?>

Adding Form elements

 
$input = $dom->createElement('input');
$domAttribute = $dom->createAttribute('type');
$domAttribute->value = 'text';
$input->appendChild($domAttribute);
$domAttribute = $dom->createAttribute('name');
$domAttribute->value = 'e-mail';
$input->appendChild($domAttribute);
$dom->appendChild($input);
//The above code will output:
input type="text" name="e-mail">
?>

Creating Table

 
$table = $dom->createElement('table');
$domAttribute = $dom->createAttribute('id');
$domAttribute->value = 'my_table';

$tr = $dom->createElement('tr');
$table->appendChild($tr);

$td = $dom->createElement('td', 'Label');
$tr->appendChild($td);

$td = $dom->createElement('td', 'Value');
$tr->appendChild($td);

$table->appendChild($domAttribute);
$dom->appendChild($table);

//The above code will output:
table id="my_table">
tbody>
tr>
td>Label/td>
td>Value/td>
/tr>
/tbody>
/table>
?>

A Complex Example

 
$dom = new DOMDocument('1.0');//Create new document

//Create the CSS styles
$css_text = '';
$css_text .= 'body';
$css_text .= '#my_table';
$css_text .= '#my_table th';
$css_text .= '#my_table td';
$css_text .= '#my_table td:first-child';

$style = $dom->createElement('style', $css_text);//Create new tag with the css tags

$domAttribute = $dom->createAttribute('type');//Create the new attribute

$domAttribute->value = 'text/css';//Add value to attribute

$style->appendChild($domAttribute);//Add the attribute to the style tag

$dom->appendChild($style);//Add the style tag to document

//Add the form
$form = $dom->createElement('form');
$dom->appendChild($form);
$formAttribute = $dom->createAttribute('method');
$formAttribute->value = 'post';
$form->appendChild($formAttribute);

//Add the table
$table = $dom->createElement('table');
$tableAttribute = $dom->createAttribute('id');
$tableAttribute->value = 'my_table';
$table->appendChild($tableAttribute);

//Add new row
$tr = $dom->createElement('tr');
$table->appendChild($tr);

//Add new column
$th = $dom->createElement('th', 'Generate HTML using PHP');
$tr->appendChild($th);
$thAttribute = $dom->createAttribute('colspan');
$thAttribute->value = '2';
$th->appendChild($thAttribute);


//Add new row
$tr = $dom->createElement('tr');
$table->appendChild($tr);

//Add new column
$td = $dom->createElement('td', 'First Name');
$tr->appendChild($td);

//Add new column
$td = $dom->createElement('td');
$tr->appendChild($td);

//Add input element to column
$input = $dom->createElement('input');
$td->appendChild($input);
$tdAttribute = $dom->createAttribute('type');
$tdAttribute->value = 'text';
$input->appendChild($tdAttribute);
$tdAttribute = $dom->createAttribute('name');
$tdAttribute->value = 'f_name';
$input->appendChild($tdAttribute);

//Add new row
$tr = $dom->createElement('tr');
$table->appendChild($tr);

//Add new column
$td = $dom->createElement('td', 'Email');
$tr->appendChild($td);

//Add new column
$td = $dom->createElement('td');
$tr->appendChild($td);

//Add input element to column
$input = $dom->createElement('input');
$td->appendChild($input);
$tdAttribute = $dom->createAttribute('type');
$tdAttribute->value = 'text';
$input->appendChild($tdAttribute);
$tdAttribute = $dom->createAttribute('name');
$tdAttribute->value = 'e-mail';
$input->appendChild($tdAttribute);

//Add new row
$tr = $dom->createElement('tr');
$table->appendChild($tr);

//Add new column
$td = $dom->createElement('td', 'Gender');
$tr->appendChild($td);

//Add new column
$td = $dom->createElement('td');
$tr->appendChild($td);

//Add input element to column
$select = $dom->createElement('select');
$td->appendChild($select);
$tdAttribute = $dom->createAttribute('name');
$tdAttribute->value = 'gender';
$select->appendChild($tdAttribute);
//Add options to select box
$opt = $dom->createElement('option', 'Male');
$domAttribute = $dom->createAttribute('value');
$domAttribute->value = 'male';
$opt->appendChild($domAttribute);
$select->appendChild($opt);

$opt = $dom->createElement('option', 'Female');
$domAttribute = $dom->createAttribute('value');
$domAttribute->value = 'female';
$opt->appendChild($domAttribute);
$select->appendChild($opt);


//Add new row
$tr = $dom->createElement('tr');
$table->appendChild($tr);

//Add new column
$td = $dom->createElement('td', 'Interest');
$tr->appendChild($td);

//Add new column
$td = $dom->createElement('td');
$tr->appendChild($td);

//Add input element to column
$radio = $dom->createElement('input');
$td->appendChild($radio);
$radAttribute = $dom->createAttribute('type');
$radAttribute->value = 'radio';
$radio->appendChild($radAttribute);
$radAttribute = $dom->createAttribute('name');
$radAttribute->value = 'interest';
$radio->appendChild($radAttribute);
$radAttribute = $dom->createAttribute('id');
$radAttribute->value = 'php';
$radio->appendChild($radAttribute);

$label = $dom->createElement('label', 'PHP');
$labelAttribute = $dom->createAttribute('for');
$labelAttribute->value = 'php';
$label->appendChild($labelAttribute);
$td->appendChild($label);

$radio = $dom->createElement('input');
$td->appendChild($radio);
$radAttribute = $dom->createAttribute('type');
$radAttribute->value = 'radio';
$radio->appendChild($radAttribute);
$radAttribute = $dom->createAttribute('name');
$radAttribute->value = 'interest';
$radio->appendChild($radAttribute);
$radAttribute = $dom->createAttribute('id');
$radAttribute->value = 'jquery';
$radio->appendChild($radAttribute);

$label = $dom->createElement('label', 'jQuery');
$labelAttribute = $dom->createAttribute('for');
$labelAttribute->value = 'jquery';
$label->appendChild($labelAttribute);
$td->appendChild($label);

//Add new row
$tr = $dom->createElement('tr');
$table->appendChild($tr);

//Add new column
$td = $dom->createElement('td');
$tr->appendChild($td);
$tdAttribute = $dom->createAttribute('colspan');
$tdAttribute->value = '2';
$td->appendChild($tdAttribute);

//Add input element to column
$input = $dom->createElement('input');
$td->appendChild($input);
$tdAttribute = $dom->createAttribute('type');
$tdAttribute->value = 'submit';
$input->appendChild($tdAttribute);
$tdAttribute = $dom->createAttribute('value');
$tdAttribute->value = 'Sign-Up';
$input->appendChild($tdAttribute);


//Add table to form
$form->appendChild($table);

echo $dom->saveHTML();
?>

Источник

Как вставить HTML, CSS и JS в PHP-код?

Когда вы разрабатываете свой модуль, то иногда прибегаете к помощи верстки (HTML и CSS) и дополнительным скриптам.

Все это можно подключать отдельно – что-то в теле страницы, что-то в отдельных файлах. Но некоторые дополнения лучше вставлять непосредственно в сам PHP-файл.

Сегодня я покажу два варианта, как можно вставить HTML, CSS или JavaScript в код PHP.

Первый вариант вставки элементов в PHP-код

Я думаю, что если вы хоть немного знакомы с PHP, то знаете, что такое «echo» (тег, с помощью которого вы можете вывести сообщение на экран).

Вот с помощью него и можно вывести один из перечисленных ранее кодов. Пример:

   "; echo $content; ?>

На что здесь стоит обратить внимание? Кавычки. Если вы используете внешние кавычки в виде » «, то внутренние кавычки элементов должны быть ‘ ‘ и наоборот, иначе вы получите ошибку. Если вы принципиально хотите использовать одинаковые и внешние, и внутренние кавычки, то во внутренних ставьте знак экранизации:

   "; echo $content; ?>

В этом случае все будет работать корректно.

Второй вариант вставки элементов в PHP-код

Этот вариант мне нравится куда больше, чем первый. Здесь мы будем также использовать «echo», как и в предыдущем варианте, но добавим еще элемент «HTML»:

Сюда вы можете вставлять любой элемент, будь то HTML-код или же JavaScript. Кавычки здесь не играют роли (можете вставить любые), а по желанию можно внедрить переменные для вывода:

 "; echo    HTML; ?>

Весьма удобный способ для реализации ваших идей.

Источник

Create HTML Elements Using PHP: html_element Class

I love creating HTML elements using the MooTools JavaScript library. It’s easy, fast, and the JavaScript code to create the element is beautiful. That got me thinking — why don’t I do this using PHP? When you build as many dynamic CMS-like websites as me, you end up having to manipulate single HTML element attributes with a bunch of if/else logic and the code can start looking ugly.

I took about a half hour to throw together the following PHP class. It’s small, easy to use, and produces beautiful code—just like Moo!

The PHP

/* 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 = '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'].'type.'>'; > else < $build.= ' />'; > //return it return $build; > /* spit it out */ function output() < echo $this->build(); > >

The class is pretty simple. When you instantiate the class, you feed it the element type. Once the element is created, you use get() to retrieve values and set() (key and value OR array key=>value) to set values. You can get rid of a specified attribute using remove() or all attribute key=>values using clear() . You can inject html_elements into other html_elements by using inject() . You can get the raw HTML of the element using build() or you can use the output() function to echo out the HTML. Important: use the «text» attribute to add text/HTML inside an element.

Example Uses

/* test case - simple link */ $my_anchor = new html_element('a'); $my_anchor->set('href','https://davidwalsh.name'); $my_anchor->set('title','David Walsh Blog'); $my_anchor->set('text','Click here!'); $my_anchor->output(); //Click here! /* test case - br tag */ echo '
'; $my_anchor = new html_element('br'); $my_anchor->output(); // 
/* test case - sending an array to set */ echo '
'; $my_anchor = new html_element('a'); $my_anchor->set('href','https://davidwalsh.name'); $my_anchor->set(array('href'=>'http://cnn.com','text'=>'CNN')); $my_anchor->output(); //CNN /* test case - injecting another element */ echo '
'; $my_image = new html_element('img'); $my_image->set('src','cnn-logo.jpg'); $my_image->set('border','0'); $my_anchor = new html_element('a'); $my_anchor->set(array('href'=>'http://cnn.com','title'=>'CNN')); $my_anchor->inject($my_image); $my_anchor->output(); //  

Have any ideas for this class? Share them!

Источник

Читайте также:  Https api telegram org bot php
Оцените статью