codeigniter avoiding html div's - php

Is there a proper syntax to avoid div's in codeigniter?
I don't really like opening and closing tags all the time...
<div class="theForm">
<?php
echo form_open('edit/links');//this form uploads
echo "Enter the Name: ". form_input('name','name');
echo "Enter the Link: ". form_input('url','url');
echo " ".form_submit('submit', 'Submit');
echo form_close();
if (isset($linksQuery) && count($linksQuery)){
foreach($linksQuery as $link){
echo anchor($link['link'], $link['name'].".", array("class" => "links"));
echo form_open('edit/links',array('class' => 'deleteForm'));
echo form_hidden('name',$link['name']);
echo " ".form_submit('delete','Delete');
echo form_close();
echo br(2);
}
}
?>
</div>

You could write a small helper like this:
<?php
function div_open($class = NULL, $id = NULL)
{
$code = '<div ';
$code .= ( $class != NULL ) ? 'class="'. $class .'" ' : '';
$code .= ( $id != NULL ) ? 'id="'. $id .'" ' : '';
$code .= '>';
return $code;
}
function div_close()
{
return '</div>';
}
echo div_open('some_class', 'some_id');
echo 'some content...';
echo div_close();
?>
will produce:
<div class="some_class" id="some_id" >some content...</div>

Related

How to add a for each loop in php?

i have an issues in my code below.
In days and time i want to add a loop, it s because i want to be able to get multiple different operating hours row. I ll add a repeater in my custom field.
And for now it s allow me to get only one row.
<ul>
<?php foreach($locations as $location) {
$title = get_the_title($location);
$address = '';
$address .= get_field('address', $location) . '<br>';
$address .= get_field('city', $location) . ', ';
$address .= get_field('state', $location) . ', ';
$address .= get_field('zip_code', $location);
$hours = get_field('days_open', $location);
$phone = get_field('contact_number', $location);
$email = get_field('contact_email', $location);
?>
<li>
<h3><?php echo $title; ?></h3>
<address><?php echo $address; ?></address>
<?php if($phone) { ?>
<?php echo $phone; ?>
<?php }; ?>
<?php if($email) { ?>
<?php echo $email; ?>
<?php }; ?>
<?php
if($hours && $hours[0]['days']
) {
echo $hours[0]['days'] . ': ';
}
?>
<?php
if($hours && $hours[0]['times']
) {
echo $hours[0]['times'];
}
?>
</li>
<?php
}
?>
</ul>
So i think my solution it s to add a foreach loop, can you help for that?
Thank you in advance cheers!
May be this is what you are looking for?
if(is_array($hours[0]['days'])){
foreach($hours[0]['days'] as $day)
{
echo $day . ': ';
}
}
if(is_array($hours[0]['times'])){
foreach($hours[0]['times'] as $time)
{
echo $time . ': ';
}
}
So I found the solutions it was :
<?php
if(is_array($hours)){
foreach($hours as $day)
{
echo $day['days'] . ': ';
echo $day['times'];
echo '<br />';
}
} ?>

How to rewrite an echo function to a return value for a Wordpress theme

I am new to PHP and I am glad that I have written the following function (which works as it should) on my own so far:
function get_latest_posts() {
echo '<div class="latest-posts">';
echo '<div class="brick_list">';
$args = array(
post_type => 'post',
posts_per_page => 3
);
$latestposts_query = new WP_Query($args);
if ( $latestposts_query->have_posts() ) : while ( $latestposts_query->have_posts() ) : $latestposts_query->the_post();
echo ' <div ';
post_class("brick_item" . $termString );
echo ' onclick="location.href=\'';
the_permalink();
echo ' \'"> ';
echo ' <div class="brick_item-image"> ';
if ( has_category( 'sample' ) ) {
echo ' <img src="/wp-content/uploads/placeholder_1.png" /> ';
} elseif ( has_post_thumbnail() ) {
the_post_thumbnail();
} else {
echo ' <img src="/wp-content/uploads/placeholder_2.png" /> ';
}
echo ' </div> ';
echo ' <div class="brick_item-header"> ';
echo ' <h4><a href=" ';
the_permalink();
echo ' "> ';
the_title();
echo ' </a></h4> ';
echo ' </div> ';
echo ' </div> ';
endwhile; else :
get_template_part('template_parts/content','error');
endif;
wp_reset_postdata();
echo '</div>';
echo '</div>';
}
add_shortcode( 'get_latest_posts', 'get_latest_posts' );
But now I definitly need your help...
As you can see I want to use this function in a shortcode. Currently it displays first on my page, and Google says, this is because I am echoing the content and I would need to give a return value.
How do I do this?? Is it just replacing the word "echo" with the word "return" ? I have no idea...
I have condensed a few statements together for readability but here's what that would look like:
function get_latest_posts() {
$return = '<div class="latest-posts"><div class="brick_list">';
$args = array(
post_type => 'post',
posts_per_page => 3
);
$latestposts_query = new WP_Query($args);
if ( $latestposts_query->have_posts() ) : while ( $latestposts_query->have_posts() ) : $latestposts_query->the_post();
$return .= ' <div ' . post_class("brick_item" . $termString ) . ' onclick="location.href=\'' . get_permalink() . '\'"> ';
$return .= '<div class="brick_item-image">';
if ( has_category( 'sample' ) ) {
$return .= '<img src="/wp-content/uploads/placeholder_1.png" />';
} elseif ( has_post_thumbnail() ) {
$return .= get_the_post_thumbnail();
} else {
$return .= '<img src="/wp-content/uploads/placeholder_2.png" />';
}
$return .= '</div> <div class="brick_item-header"> <h4>' . the_title('','',false) . '</h4></div></div>';
endwhile; else :
get_template_part('template_parts/content','error');
endif;
wp_reset_postdata();
$return .= '</div></div>';
return $return;
}
add_shortcode( 'get_latest_posts', 'get_latest_posts' );

Check checkbox hit button but checkbox will not stay checked

I am not sure how to keep my checkbox checked after I hit the Apply button. I am thinking I have to add is_set to the output but I am not sure how or where to add it in. Here is my code below any help would be great.
<div id="product-filter-options">
<form method="GET">
<?php
$scooters = $_GET['scooters'];
$product_type = $_GET['product_type'];
$bike_sub_category = $_GET['bike_sub_category'];
$model_year = $_GET['model_year'];
?>
<?php
function get_terms_chekboxes($taxonomies, $args) {
$terms = get_terms($taxonomies, $args);
foreach($terms as $term) {
$output .= '<span><label for="'.$term->slug.'"><input type="checkbox" id="'.$term->slug.'" name="'.$taxonomies.'" value="'.$term->slug.'" >' .$term->name.'</label></span>';
}
return $output;
}
echo '<div class="check-contain">';
echo '<h4>Bicycle Brand</h4>';
echo get_terms_chekboxes('scooters', $args = array('hide_empty'=>true));
echo '<span class="slide-show-more">See More</span>';
echo '</div>';
echo '<div class="check-contain">';
echo '<h4>Bicycle Type</h4>';
echo get_terms_chekboxes('product_type', $args = array('hide_empty'=>true));
echo '<span class="slide-show-more">See More</span>';
echo '</div>';
echo '<div class="check-contain">';
echo '<h4>Bicycle Sub-Type</h4>';
echo get_terms_chekboxes('bike_sub_category', $args = array('hide_empty'=>true));
echo '<span class="slide-show-more">See More</span>';
echo '</div>';
echo '<div class="check-contain">';
echo '<h4>Model Year</h4>';
echo get_terms_chekboxes('model_year', $args = array('hide_empty'=>true));
echo '<span class="slide-show-more">See More</span>';
echo '</div>';
?>
<button type="submit">Apply</button>
Thanks in advance.

change the class for the first row extend from mysql with PHP

I have a banner that used from bootstrap and, the first slider on this banner should have class='item active' the rest of the sliders should have class='item' I am getting my sliders from my database
so far that what I try to do.
<?php
$getBanner = $db->prepare("SELECT * FROM banner_english");
if ($getBanner->execute()) {
$results = $getBanner->get_result();
while ($b = $results->fetch_array()) {
$bannerImages = array($b['image']);
foreach ($bannerImages as $image) {
if ($image[0]) {
echo '<div class="item active">
<img src="../images/en_banner/' . $image . '" alt="Koueider">
</div>';
} else {
echo '<div class="item">
<img src="../images/en_banner/' . $image . '" alt="Koueider">
</div>';
var_dump($bannerImages);
}
}
}
}
?>
still not working as expected
var_dump
array (size=1)
0 => string '06.jpg' (length=6)
array (size=1)
0 => string '03.jpg' (length=6)
I see that the var_dump is 0 for all items what did I do wrong here?
This is a fix to the old code:
<?php
$getBanner = $db->prepare("SELECT image FROM banner_english");
if ($getBanner->execute()) {
$results = $getBanner->get_result();
$is_first = true;
while ($b = $results->fetch_array()) {
if ($is_first) {
echo '<div class="item active">
<img src="../images/en_banner/' . $b[0] . '" alt="Koueider">
</div>';
$is_first = false;
} else {
echo '<div class="item">
<img src="../images/en_banner/' . $b[0] . '" alt="Koueider">
</div>';
var_dump($bannerImages);
}
}
}
?>
Change the code like this:
<?php
$getBanner = $db->prepare("SELECT * FROM banner_english");
if ($getBanner->execute()) {
$results = $getBanner->get_result();
$rows = $results->fetch_all(MYSQLI_ASSOC);
$ind = 0;
foreach ($rows as $image) {
if ($ind == 0) {
echo '<div class="item active">
<img src="../images/en_banner/' . $image . '" alt="Koueider">
</div>';
$ind++;
} else {
echo '<div class="item">
<img src="../images/en_banner/' . $image . '" alt="Koueider">
</div>';
var_dump($bannerImages);
}
}
}
?>

PHP Class to Generate HTML?

Anyone know of any classes written for php that can clean up your code a bit?
Something like,
$htGen = new HTMLGenerator();
$htGen->newDOM('div', 'here is what goes in the div', 'optionalID', 'optionalClass');
Or does that just sound redundant?
I end up with some complex looking mish-mashes of html and php sometimes that I feel could be simplified a bit eg my latest cms bit;
foreach($details as $detail){
$d = unserialize($detail);
if($ad){
print_r($d); // <-- VIEW DETAIL OBJECT IN WHOLE.
}else{
if($d->get_info('orphan')){
echo '<li class="classRow orphan">' . "\n";
echo '<div class="orphan" style="display:none">orphan</div>' . "\n";
}else{
echo '<li class="classRow">' . "\n";
echo '<div class="orphan" style="display:none"></div>' . "\n";
}
echo '<div class="classNumbers" id="' . $d->get_info('class ID') . '" style="display:none"></div>' . "\n";
echo '<div class="rowBG" style="overflow:hidden;width:100%">';
echo '<div class="startTime"></div>' . "\n";
echo '<div class="details"><span class="classes">' . $d->get_info('class number') . '</span> - <input class="detailInput" type="text" value="' . $d->get_info('class description') . '"/><div class="editButton"><a class="editExpand">options(+)</a></div></div>' . "\n";
echo '<div class="interval">';
echo '<input class="intervalInput" type="text" value="' . $d->get_info('interval') . '" maxlength="5"/>';
echo '</div>' . "\n";
echo '<div class="numRiders"><input class="numRidersInput" type="text" value="' . $d->get_info('num riders') . '"/></div>' . "\n";
echo '</div>';
echo '<div class="classOptions">' . "\n";
echo '<div class="selectRingMove">Move to Ring:<select id="ringSwap"><option>Select A Ring</option>' . get_ring_options() . '</select></div>' . "\n";
if($d->get_info('online sign up') != 'false'){
echo '<div class="signUpContainer">Sign-Up<input type="checkbox" class="signUp" checked/></div>' . "\n";
}else{
echo '<div class="signUpContainer">Sign-Up<input type="checkbox" class="signUp"/></div>' . "\n";
}
if($d->get_info('water and drag')){
echo '<div class="wdBoxContainer"><select id="wdDescrip"><option>WATER AND DRAG</option><option>COURSE CHANGE & WALK</option><option>OTHER</option></select><input type="checkbox" class="wdBox" checked/><input type="text" value="' . $d->get_info('water and drag') . '" maxlength="2" class="wdInput"> min</div>' . "\n";
}else{
echo '<div class="wdBoxContainer"><select id="wdDescrip"><option>WATER AND DRAG</option><option>COURSE CHANGE & WALK</option><option>OTHER</option></select><input type="checkbox" class="wdBox"/><input type="text" value="20" maxlength="2" class="wdInput"> min</div>' . "\n";
}
if($d->get_info('ghost riders')){
echo '<div class="ghostRidersContainer">Ghost Riders<input type="checkbox" checked class="ghostBox"><input type="text" maxlength="2" class="ghostRiderInput" value="' . $d->get_info('ghost riders') . '"></div>' . "\n";
}else{
echo '<div class="ghostRidersContainer">Ghost Riders<input type="checkbox" class="ghostBox"><input type="text" maxlength="2" class="ghostRiderInput"></div>' . "\n";
}
echo '</div>' . "\n";
echo '</li>' . "\n";
if($d->get_info('water and drag')){
echo '<li class="waterAndDragRow" style="display:block;"><span class="wdStartTime">08:33am</span> - <span class="wdEndTime">08:34am</span> <input type="text" class="wdDescription" value="' . $d->get_info('water and drag description') . '"></li>';
}
}
}
Or, if you know of a cleaner way to write long blocks of intermingled php vars and html... (not a big fan of EOF>>>)
Thanks in advance.
I guess it could be done with http://www.php.net/manual/en/class.domdocument.php. But that isn't really a good way to do it.
I agree that your code code sample isn't very clear, you could consider something like:
<ul>
<?php foreach ($items as $item): ?>
<li>
<?=$item['something']?>
<?php if ($item['foo'] == 'bar'): ?>
<ul>
<li>bar</li>
</ul>
<?php else: ?>
<ul>
<li>foo</li>
</ul>
<?php endif; ?>
</li>
<?php endforeach; ?>
<ul>
That's a lot better imho, I use it like that in my views.
Btw, you should validate your html output. For example, a div-element isn't allowed in a li-element.
edit:
Obviously, the following code:
<?php if ($item['foo'] == 'bar'): ?>
<ul>
<li>bar</li>
</ul>
<?php else: ?>
<ul>
<li>foo</li>
</ul>
<?php endif; ?>
Could be replaced by:
<ul>
<li><?=($item['foo'] == 'bar' ? 'bar' : 'foo')?></li>
</ul>
I'm working on a simple DSL that addresses this common task. It's called htmlgen, mirrored on packagist.
Here's an example
use function htmlgen\html as h;
h('#wrapper',
h('h1.title', 'Hello, World'),
h('p',
h('comment', 'link to something'),
h('a', ['href'=>'https://duckduckgo.com'], 'search the internet')
)
);
Here's the output (actual output does not have whitespace)
<div id="wrapper">
<h1 class="title">Hello, World</h1>
<p>
<!-- link to something -->
search the internet
</p>
</div>
It's very new but at ~200 lines of source, it's already very powerful. Fork it and make adjustments or send me a note with suggestions.
The main idea of generating HTML is to keep HTML as is.
Just divide your script into 2 parts: prepare data part and display data part. A latter one should contain mostly HTML with some PHP control structures. Of course, there should be as less PHP code as possible. Move all unnecessary PHP code into first part.
Well to sum up all of the above:
there should be nothing to unserialize in the $details array. Have your data prepared already
<? foreach ($details as $d): ?>
<li class="classRow orphan">
<div class="orphan" style="display:none"><? if ($d->get_info('orphan')): ?>orphan<? endif ?></div>
<div class="classNumbers" id="<?= $d->get_info('class ID') ?>" style="display:none"></div>
<div class="rowBG" style="overflow:hidden;width:100%">
<div class="startTime"></div>
<div class="details">
<span class="classes"><?= $d->get_info('class number') ?></span> -
<input class="detailInput" type="text" value="<?= $d->get_info('class description') ?>"/>
<div class="editButton">
<a class="editExpand">options(+)</a>
</div>
</div>
<div class="interval">
<input class="intervalInput" type="text" value="<?= $d->get_info('interval') ?>" maxlength="5"/>
</div>
<div class="numRiders">
<input class="numRidersInput" type="text" value="<?= $d->get_info('num riders') ?>"/>
</div>
</div>
<div class="classOptions">
<div class="selectRingMove">Move to Ring:
<select id="ringSwap">
<option>Select A Ring</option>
<?= foreach (get_ring_options() as $value => $option): ?>
<option value="<?=$value?>"><?=$option?></option>
<? endforeach ?>
</select>
</div>
<div class="signUpContainer">Sign-Up
<input type="checkbox" class="signUp" <? if (!$d->get_info('online sign up'): ?>checked<? endif ?>/>
</div>
and so on.
The main rule should be DRY: Do not Repeat Yourself.
Do not repeat blocks of code if there is only one word difference.
But enclose that word into condition
Note that get_ring_options() was replaced with proper code.
Do not make functions that return HTML, but an array instead.
Instead of a class, consider a library of functions to generate HTML. I didn't use a class to make the code that you end up writing concise but expressive. With a class you must create an instance and use that variable, or make the methods static and write static references.
With this technique creating HTML for an image that is a link looks like this:
a('/example/url', img('image_url', $altText));
This is based on a script I once created. First the generic functions to generate HTML elements and attributes:
function tag($tag, $text, $attributes = array()) {
return "<$tag" . attributesToArray($attributes) . ">$text</$tag>";
}
function minimizedTag($tag, $attributes = array()) {
return "<$tag" . attributesToArray($attributes) . " />";
}
function attributesToArray($attributes = array()){
$a = '';
foreach ($attributes as $attribute => $value) {
$a .= " $attribute='$value'";
}
return $a;
}
Then add functions named according to the HTML elements they create, like a() and img() to create a link and image:
function a($link, $text, $attributes = array()) {
$a = array('href' => $link);
foreach ($attributes as $attribute => $value) {
$a[$attribute] = $value;
}
return tag('a', $text, $a);
}
function img($url, $alt = null) {
$a = array('src' => $url);
if (!is_null($alt)){
if (is_array($alt)){
$a = array_merge($a, $alt);
} else {
$a['alt'] = $alt;
}
}
return minimizedTag('img', $a);
}
Choose the parameters to pass common attributes wisely to make the library easier to use.
I'll probably get downvoted for recommending short tags, but here's what I do. I put all the <? and ?> tags at column 1 so that the code reads like a mix of PHP and HTML. No echo statements is the goal.
foreach ($details as $detail) {
$d = unserialize($detail);
if ($ad) {
print_r($d); // <-- VIEW DETAIL OBJECT IN WHOLE.
}
else {
if ($d->get_info('orphan')) {
?> <li class="classRow orphan">
<div class="orphan" style="display:none">orphan</div>
<? }
else {
?> <li class="classRow">
<div class="orphan" style="display:none"></div>
<? }
?> <div class="classNumbers" id="<?= $d->get_info('class ID') ?>"
style="display:none"></div>
<div class="rowBG" style="overflow:hidden;width:100%">
<div class="startTime"></div>
<div class="details">
<span class="classes"><?= $d->get_info('class number') ?></span> -
<input class="detailInput" type="text" value="<?= $d->get_info('class description') ?>"/>
<div class="editButton">
<a class="editExpand">options(+)</a>
</div>
</div>
<div class="interval">
<input class="intervalInput" type="text" value="<?= $d->get_info('interval') ?>" maxlength="5"/>
</div>
<div class="numRiders">
<input class="numRidersInput" type="text" value="<?= $d->get_info('num riders') ?>"/>
</div>
</div>
<div class="classOptions">
<div class="selectRingMove">
Move to Ring:
<select id="ringSwap">
<option>Select A Ring</option>
<?= get_ring_options() ?>
</select>
</div>
<? if ($d->get_info('online sign up') != 'false') {
?> <div class="signUpContainer">
Sign-Up
<input type="checkbox" class="signUp" checked/>
</div>
<? }
else {
?> <div class="signUpContainer">
Sign-Up
<input type="checkbox" class="signUp"/>
</div>
<? }
if ($d->get_info('water and drag')) {
?> <div class="wdBoxContainer">
<select id="wdDescrip">
<option>WATER AND DRAG</option>
<option>COURSE CHANGE & WALK</option>
<option>OTHER</option>
</select>
<input type="checkbox" class="wdBox" checked/>
<input type="text" value="<?= $d->get_info('water and drag') ?>" maxlength="2" class="wdInput"> min
</div>
<? }
else {
?> <div class="wdBoxContainer">
<select id="wdDescrip">
<option>WATER AND DRAG</option>
<option>COURSE CHANGE & WALK</option>
<option>OTHER</option>
</select>
<input type="checkbox" class="wdBox"/>
<input type="text" value="20" maxlength="2" class="wdInput"> min
</div>
<? }
if ($d->get_info('ghost riders')) {
?> <div class="ghostRidersContainer">
Ghost Riders
<input type="checkbox" checked class="ghostBox">
<input type="text" maxlength="2" class="ghostRiderInput" value="<?= $d->get_info('ghost riders') ?>">
</div>
<? }
else {
?> <div class="ghostRidersContainer">
Ghost Riders
<input type="checkbox" class="ghostBox">
<input type="text" maxlength="2" class="ghostRiderInput">
</div>
<? }
?> </div>
</li>
<? if ($d->get_info('water and drag')) {
?> <li class="waterAndDragRow" style="display:block;">
<span class="wdStartTime">08:33am</span> -
<span class="wdEndTime">08:34am</span>
<input type="text" class="wdDescription" value="<?= $d->get_info('water and drag description') ?>">
</li>
<? }
}
}
In regards to PHP classes to generate HTML, you could use http://api20.cakephp.org/class/html-helper an object from the cake PHP framework.
The others have already addressed your not so clean code.
It uses this format: div( $class = NULL, $text = NULL, $options = array ( ) )
why not create your own clases?? or at least some functions... and i saw that you use alot of IF, you may clean it using vairables like when you have
if($d->get_info('ghost riders')){
echo '<div class="ghostRidersContainer">Ghost Riders<input type="checkbox" checked class="ghostBox"><input type="text" maxlength="2" class="ghostRiderInput" value="' . $d->get_info('ghost riders') . '"></div>' . "\n";
}else{
echo '<div class="ghostRidersContainer">Ghost Riders<input type="checkbox" class="ghostBox"><input type="text" maxlength="2" class="ghostRiderInput"></div>' . "\n";
}
you could write:
$check = ($d->get_info('ghost riders'))?"checked":"";
echo '<div class="ghostRidersContainer">Ghost Riders<input type="checkbox" '.$check.' class="ghostBox"><input type="text" maxlength="2" class="ghostRiderInput" value="' . $d->get_info('ghost riders') . '"></div>' . "\n";
it will look cleaner :) I've created a Form class that helps me when i have to create forms and the code is more legible
Do not mix html and php code!
I would do this: https://github.com/HanKruma/Tag-Generator
"Tag gen"
<?php
namespace Main;
/**
* Description of Tag
*
* #author HanKrum
*/
class Tag {
private $_tags = ['doctype', 'br', 'hr', 'input', 'meta', 'base', 'basefont', 'img', 'source'];
public function __call($name, $arguments) {
$attr = null;
$text = null;
if (\in_array($name, $this->_tags)) {
$name = $name == $this->_tags[0] ? '!' . $name . ' html' : $name;
foreach ($arguments as $v) {
$attr .= ' ' . $v;
}
return '<' . $name . $attr . '>' . "\n";
}
$br = 0;
$count = \count($arguments);
foreach ($arguments as $v) {
$br ++;
if ($br == $count) {
$text = $v;
} else {
if (!$v) {
$space = null;
} else {
$space = ' ';
}
$attr .= $space . $v;
}
}
return '<' . $name . $attr . '>' . $text . '</' . $name . '>' . "\n";
}
}
And use this that:
<?php
$ob = new \Main\Tag();
echo $ob->input('class="doc"', 'placeholder="Title"', 'name="title"');
echo $ob->span(null, 'Text');
exit($ob->button('class="submit"', 'Write');
For those looking for the simple start. This is enough to generate a wide variety of elements.
This will create any kind of element, give some content, a class, and an id.
You will have to handle special cases yourself, if you are using it in your app.
<?php
/**
* HTML - Simplest html element builder
* - #param1 Element name
* - #param2 Class name
* - #param3 ID
* - #param2 Element content
*/
class HTML{
/**
* Create a new html element
*/
private static function core($element, $content) {
return "<" . $element . ">" . $content . "</" . $element . ">";
}
/**
* Add a new param to a html element
*/
private static function addParam($elem, $param, $value) {
if (is_null($value)){return $elem;}
return implode(" $param=\"" . $value . '">', explode(">", $elem, 2));
}
/**
* Return an element with a class and an id
*/
public static function create($element, $content=null, $class=null, $id=null) {
return self::addParam(self::addParam(self::core($element, $content), "class", $class) , "id", $id);
}
}
// Examples
echo HTML::create("div", "This is it!", "redclass", "niceid");
echo PHP_EOL;
$html = new HTML();
echo HTML::create("button", "Click me!", "button", "48151");
echo PHP_EOL;
echo $html->create("p", "A paragraph");
echo PHP_EOL;
echo $html->create("h3", "Hello world!");
// OUTPUT
//<div class="redclass" id="niceid">This is wtf</div>
//<button class="button" id="48151">Click me!</button>
//<p>A paragraph</p>
//<h3>Hello world!</h3>
.redclass {background: red}
<div class="redclass" id="niceid">This is it!</div>
<button class="button" id="48151">Click me!</button>
<p>A paragraph</p>
<h3>Hello world!</h3>
Something like this?
<?php
$html->tag('doctype')->alone('html')->tag();
$html->tag('html')->lang('en');
$html->tag('head');
$html->tag('meta')->charset('utf-8')->tag();
$html->tag('meta')->httpequiv('X-UA-Compatible')->content('IE=edge')->tag();
$html->tag('meta')->name('viewport')->content('width=device-width, initial-scale=1')->tag();
$html->tag('meta')->name('description')->content('Brosta Tools')->tag();
$html->tag('meta')->name('author')->content('Brosta')->tag();
$html->tag('title')->text('Brosta Tools')->tag();
$html->tag('link')->href('assets/plugins/bootstrap/css/bootstrap.min.css')->rel('stylesheet')->tag();
$html->tag('link')->href('assets/plugins/bootstrap/css/simple-sidebar.css')->rel('stylesheet')->tag();
$html->tag('link')->href('assets/plugins/prism/css/prism.css')->rel('stylesheet')->tag();
$html->tag('link')->href('assets/plugins/normalize/css/normalize.css')->rel('stylesheet')->tag();
$html->tag('link')->href('assets/plugins/brosta/css/brosta.css')->rel('stylesheet')->tag();
$html->tag('script')->src('assets/plugins/bootstrap/js/jquery.js')->type('text/javascript')->tag();
$html->tag('script')->src('assets/plugins/bootstrap/js/bootstrap.min.js')->type('text/javascript')->tag();
$html->tag('script')->src('assets/plugins/prism/js/prism.js')->type('text/javascript')->tag();
$html->tag('script')->type('text/javascript')->text('$("#menu-toggle").click(function(e) {e.preventDefault(); $("#wrapper").toggleClass("toggled"); });')->tag();
$html->tag('script')->type('text/javascript')->text('
window.onload = function () {
var x = document.getElementsByClassName("token");
var i;
for (i = 0; i < x.length; i++) {
var variable = x[i].getAttribute("class").replace("token ", "");
var text = x[i].innerText.trim().replace("$", "");
if(!/[^a-zA-Z0-9]/.test(text) || text.indexOf("_") >= 0) {
x[i].className +=" " + variable + "-" + text;
}
}
}
')->tag();
$html->tag();
$html->tag('body')->class('brosta');
$html->include('snippets.brosta.navbar');
$html->tag('div')->class('container-fluid brosta');
$html->tag('div')->id('wrapper');
$html->tag('div')->id('sidebar-wrapper');
$html->tag('ul')->class('sidebar-nav');
$data = [
['link' => '/Instalation', 'text' => 'Instalation'],
['link' => '/Html', 'text' => 'Html']
];
foreach($data as $link)
{
$html->tag('li');
$html->tag('a')->href($link['link'])->text($link['text'])->tag();
$html->tag();
}
$html->tag();
$html->tag();
$html->tag('div')->id('page-content-wrapper');
$html->tag('div')->class('row');
$html->tag('div')->class('col-lg-12');
$html->tag('div')->class('panel panel-default');
$html->tag('div')->class('panel-heading clearfix')->text('Without Time')->tag();
$html->tag('div')->class('panel-body');
$html->tag('p')->text('Make a file in your root public server. Ex: <code class="language-php">C:\xampp\htdocs\index.php</code>')->tag();
$html->tag('pre')->class('language-php');
$html->tag('code')->class('language-php')->text($html->specialChars('views/content.php'))->tag();
$html->tag();
$html->tag();
$html->tag();
$html->tag();
$html->tag();
$html->tag();
$html->tag();
$html->tag();
$html->tag();
$html->tag();
echo $html->get();
This is a bit late, but I've recently written an object-oriented HTML generator for PHP. It supports nesting.
As an example, this...
$h = new \HTML;
echo $h::div(
'class', 'my-class',
'id', 'my-id',
$h::p(
'class', 'paragraph',
'It was a dark and stormy night, at least according to the beginning of the book.'
)
);
...will create this markup (without spaces between the tags)...
<div class="my-class" id="my-id">
<p class="paragraph">It was a dark and stormy night, at least according to the book.</p>
</div>
Hope you find it useful!
studiowbe/html is the right package for me. It has a sound API, with chaining, and it is enabled on Composer.
$link = new Studiow\HTML\Element("a");
$link->setInnerHTML("Documents")
->setAttribute("href", "/documents")
->addClass("button")
->addClass("button-documents")
->setAttribute('title', "Go to documents");
echo (string) $link; // Outputs Documents
The Tag and Attribute classes are simple to understand and they get the job done.
A simple usage example with a single tag
$div = new Tag("div");
$class = new Attribute("class");
$class->addItem("class_a");
$class->addItem("class_b");
$div->addAttribute($class);
echo $div->build();
/**
* Output:
*
* <div class='class_a class_b'></div>
*/
A more complex usage example with multiple tags
a. Creating tags
$mainDiv = new Tag("div");
$innerDiv = new Tag("div");
$h1 = new Tag("h1");
$h2 = new Tag("h2");
$h3 = new Tag("h3");
b. Creating attributes
$class = new Attribute("class");
$class->addItem("someClass");
$style = new Attribute("style", ";");
$style->addItem("font-color: blue");
$style->addItem("font-size: 10px");
c. Adding attributes
$innerDiv->addAttribute($class);
$h3->addAttribute($style);
d. Adding plain text
$h1->setPlainText("This is header one");
$h2->setPlainText("This is header two");
$h3->setPlainText("This is header three");
e. Adding tags
$innerDiv->addTag($h1);
$innerDiv->addTag($h2);
$mainDiv->addTag($innerDiv);
$mainDiv->addTag($h3);
f. Building tags
echo $mainDiv->build();
/**
* Output (with indentation):
*
* <div>
* <div class='someClass'>
* <h1>This is header one</h1>
* <h2>This is header two</h2>
* </div>
* <h3 style='font-color: blue;font-size; 10px'>
* This is header three
* </h3>
* </div>
*/
Tag class
<?php
final class Tag
{
protected array $innerTags = [];
protected array $attributes = [];
protected string $plainText = "";
protected string $tagName;
public function __construct($tagName)
{
$this->tagName = $tagName;
}
public function addTag(Tag $t)
{
$this->innerTags[] = $t;
}
public function addAttribute(Attribute $a)
{
$this->attributes[] = $a;
}
public function setPlainText(string $plainText)
{
$this->plainText = $plainText;
}
public function build(): string
{
if (empty($this->attributes)) {
$pattern = "<%s%s>%s</%s>";
} else {
$pattern = "<%s %s>%s</%s>";
}
return sprintf($pattern,
$this->tagName,
$this->buildAttributes(),
$this->buildInnerContent(),
$this->tagName
);
}
private function buildAttributes(): string
{
$building = [];
foreach ($this->attributes as $att) {
$building[] = $att->build();
}
return implode(" ", $building);
}
/**
* A Tag cannot have inner tags and plain text at
* the same time
*/
private function buildInnerContent(): string
{
if (empty($this->innerTags)) {
return $this->plainText;
}
return $this->buildInnerTags();
}
private function buildInnerTags(): string
{
$building = "";
foreach ($this->innerTags as $tag) {
$building .= $tag->build();
}
return $building;
}
}
Attribute class
<?php
final class Attribute
{
private string $name;
private array $items = [];
private string $itemSeparator;
public function __construct(string $name, string $itemSeparator = " ")
{
$this->name = $name;
$this->itemSeparator = $itemSeparator;
}
public function addItem(string $item)
{
$this->items[] = $item;
}
public function build(): string
{
$formattedItems = implode($this->itemSeparator, $this->items);
return "{$this->name}='{$formattedItems}'";
}
}

Categories