PHP Class to Generate HTML? - php

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}'";
}
}

Related

Make function inside echo be outputted at formatted position

I have tried many approaches to get this right, including all types of quoting, etc. I will give you my current code before explaining the situation.
function show_msgs($msgs)
{
foreach($msgs as $msg) {
echo '<div class="msg">' . $msg . '</div>' . "\n ";
}
}
function generate_msgBox()
{
global $array;
$stackoverflow =
<<<EOT
<div class="container">
<div class="msgBox">
%s
</div>
</div>
EOT;
$stackoverflow = sprintf($stackoverflow, show_msgs($array));
echo $stackoverflow;
}
generate_msgBox function currently outputs this when called:
<div class="msg">First message!</div>
<div class="msg">Seconds message!</div>
<div class="container">
<div class="alertBox">
</div>
</div>
However I need it to output this:
<div class="container">
<div class="alertBox">
<div class="msg">First message!</div>
<div class="msg">Seconds message!</div>
</div>
</div>
I tried putting function directly inside echo that is enclosed by normal quotes and I got the same result.
How do I fix this?
Echo in show_msgs function works before output of generate_msgBox function - when you call it. just return string with result of function
function show_msgs($msgs)
{
$ret = '';
foreach($msgs as $msg) {
$ret .= '<div class="msg">' . $msg . '</div>' . "\n ";
}
return $ret;
}
What about this:
function show_msgs($msgs)
{
foreach($msgs as $msg) {
echo '<div class="msg">' . $msg . '</div>' . "\n";
}
}
function generate_msgBox()
{
$stackoverflow = '<div class="container"><div class="msgBox">'.show_msgs().'</div></div>';
echo $stackoverflow;
}

Send SESSION GET information in POST contact form together with the POST fields

On the website i'm currently working on I made a list (cart idea) where customers can put products on. It works with GET method + a session, the code for the making of the session is as follows:
`<?php session_start();
require("dbconnect.php");
?>
<?php
if(!isset($_SESSION['cart'])) {
$cart = array();
$_SESSION['cart'] = $cart;
}
if(isset($_GET['action']) && $_GET['action']=="add"){
$id=intval($_GET['id']);
if(in_array($id, $_SESSION['cart'])){
if (($key = array_search($id, $_SESSION['cart'] !== false))){
unset($_SESSION['cart'][$key]);
}
}
else {
array_push($_SESSION['cart'],$id);
}
}
if(isset($_GET['action']) && $_GET['action']=="delete"){
$id = intval($_GET['id']);
if (in_array($id, $_SESSION['cart'])){
$key = array_search($id, $_SESSION['cart']);
unset($_SESSION['cart'][$key]);
}
}
?>
Nothing special, just a regular cart in a session with an array where I put all the unique product codes to remember what is on the list. Now when customers go to the page where they could send the list of product they also can select how many of each product they want. They have to fill in a number and when they are done they click on the button 'calculate (berekenen in my language)' and they get the subtotal price of all the products, the VAT and the total price. However, I want it this way that the customer can fill in their personal information plus the list plus the amounts to be send in an e-mail. I made selfmade PHP forms myself earlier but now i'm getting stuck. I use GET for the order list but I always use a POST form for my contactforms. How can I manage to make one button that sends the list plus the amounts plus the input of the contact form fields to me? At this moment I tried it as follows (and many more ways, but it all failed so far).
<main>
<div class="main-center">
<div class="offerte-container">
<form action="" method="get" value="offertelijst">
<ul class="offerte-list">
<?php
$per_page = 9;
$args = array(
'post_type'=> 'wpcproduct',
'order' => 'ASC',
'orderby' => 'menu_order',
'posts_per_page' => $per_page
);
$products = new WP_Query($args);
?>
<?php
while($products->have_posts()): $products->the_post();
$id = get_the_ID();
$title = get_the_title();
$permalink = get_permalink();
$price = get_post_meta(get_the_id(),'wpc_product_price',true);
$product_id = get_post_meta(get_the_id(), 'product_ID', true);
if(in_array($id, $_SESSION['cart'])){
echo '<li class="wpc-product-item">';
echo 'Verwijder ';
echo '<input alt="hoeveelheid" maxlengt="2" value="' .$_GET["amount$id"]. '" min="1" type="number" max="99" name="amount'.$id.'" size="3" required> </input>';
echo '<div class="item-title"> ' .$title. ' </div>';
echo '<div class="item-take"> <img width="25px" src="http://bgc-testomgeving.nl/sem/wp-content/themes/sem/images/pijltje.png" /> </div>';
echo '<div class="item-nr"> '.$product_id. '</div>';
if((isset($_GET["amount$id"]) && $_GET["amount$id"] == 1) || $_GET["amount$id"] == "" ){
if (is_numeric($price) && (floor($price) == $price)) {
echo '<div class="item-price"> €' .number_format ($price , 0 , "," , "." ). ',- </div>';
}
else {
echo '<div class="item-price"> €' .$price. '</div>';
}
echo '</li>';
}
else if(isset($_GET["amount$id"]) && floatval($_GET["amount$id"]) > 1){
changeFormat($price);
$priceTotal = number_format($price * floatval($_GET["amount$id"]), 2);
if (is_numeric($priceTotal) && (floor($priceTotal) == $priceTotal)) {
echo '<div class="item-price"> €' .$priceTotal . ',- </div>';
}
else {
echo '<div class="item-price"> €' .$priceTotal . '</div>';
}
echo '</li>';
}}
endwhile;
?>
</ul>
<input type="submit" value="Bereken"> </input>
</form>
<div class="totalprice">
<?php
(float)$total = 0;
while($products->have_posts()): $products->the_post(); {
$id = get_the_ID();
$title = get_the_title();
$permalink = get_permalink();
$price = get_post_meta(get_the_id(),'wpc_product_price',true);
$product_id = get_post_meta(get_the_id(), 'product_ID', true);
if(in_array($id, $_SESSION['cart'])){
if (is_numeric($price) && (floor($price) == $price)) {
$price = number_format($price, 2);
}
else {
$price = str_replace(',', '.', $price);
}
$total += (floatval($price) * floatval($_GET["amount$id"]));
}}
endwhile;
(String)$total;
number_format($total, 2);
$totalDecimal = str_replace('.', ',', $total);
echo 'Subtotaal: €' .$totalDecimal. '<br />';
echo 'BTW: €' . str_replace('.',',', number_format($total * 0.21,2)). '<br />';
echo 'Totaal: €' . str_replace('.',',', number_format($total * 1.21,2));
function changeFormat($var) {
if(is_numeric($var) && (floor($var) == $var)){
return number_format($var, 0) + ',-';
}
else {
if (is_numeric($var)) {
return number_format($var, 2, ',', '.');
}
else if (is_string ($var)){
return str_replace(',', '.', $var);
}
else {
echo "What the hell is dit voor een formaat?";
}
}}
?>
</div>
</div>
</div>
</main>
The calculate function and the orderlist are all working fine and i'm able to make a standard POST form as a contactform but I can't manage to get this done. I want the button 'send' to send the list plus the given amounts per product and the filled in contact forms.
The URL for this project is: http://www.bgc-testomgeving.nl/sem
Underneath the http://www.bgc-testomgeving.nl/sem/offertelijst/ page should be the contact form but every time I try to build this I demolish my perfect order list.
First of all change your form method to post.
<form action="" method="post" value="offertelijst">
Then you have to create inputs for each item in your form element. I see this you have only Amount input in your form:
echo '<input alt="hoeveelheid" maxlengt="2" value="' .$_GET["amount$id"]. '" min="1" type="number" max="99" name="amount'.$id.'" size="3" required> </input>';
Create input for each element, since user doesnt need to see those inputs you can create them as hidden element, here is one example for item title:
echo '<input type="hidden" name="title['.$id.']" value="' .$title. '"</input>';
Put this below this line
echo '<div class="item-title"> ' .$title. ' </div>';
After you created all inputs, also create second button near of this one:
<input type="submit" name="action" value="Bereken">
<input type="submit" name="action" value="Send">
So When the user click Bereken, you will do your calculation things, but if it is Send button, you will mail it to your self. here is Example code:
<?php
// if send button clicked
if($_POST["action"]=="Send")
{
/// mail to your self all element
mail("you#www.com","New Order",implode("-",$_POST));
}
?>
<main>
<div class="main-center">
<div class="offerte-container">
<form action="" method="post" value="offertelijst">
<ul class="offerte-list">
<?php
$per_page = 9;
$args = array(
'post_type'=> 'wpcproduct',
'order' => 'ASC',
'orderby' => 'menu_order',
'posts_per_page' => $per_page
);
$products = new WP_Query($args);
?>
<?php
while($products->have_posts()): $products->the_post();
$id = get_the_ID();
$title = get_the_title();
$permalink = get_permalink();
$price = get_post_meta(get_the_id(),'wpc_product_price',true);
$product_id = get_post_meta(get_the_id(), 'product_ID', true);
if(in_array($id, $_SESSION['cart'])){
echo '<li class="wpc-product-item">';
echo 'Verwijder ';
echo '<input alt="hoeveelheid" maxlengt="2" value="' .$_GET["amount$id"]. '" min="1" type="number" max="99" name="amount'.$id.'" size="3" required> </input>';
echo '<div class="item-title"> ' .$title. ' </div>';
// i added below input for example
echo '<input type="hidden" name="title['.$id.']" value="' .$title. '"</input>';
echo '<div class="item-take"> <img width="25px" src="http://bgc-testomgeving.nl/sem/wp-content/themes/sem/images/pijltje.png" /> </div>';
echo '<div class="item-nr"> '.$product_id. '</div>';
if((isset($_GET["amount$id"]) && $_GET["amount$id"] == 1) || $_GET["amount$id"] == "" ){
if (is_numeric($price) && (floor($price) == $price)) {
echo '<div class="item-price"> €' .number_format ($price , 0 , "," , "." ). ',- </div>';
}
else {
echo '<div class="item-price"> €' .$price. '</div>';
}
echo '</li>';
}
else if(isset($_GET["amount$id"]) && floatval($_GET["amount$id"]) > 1){
changeFormat($price);
$priceTotal = number_format($price * floatval($_GET["amount$id"]), 2);
if (is_numeric($priceTotal) && (floor($priceTotal) == $priceTotal)) {
echo '<div class="item-price"> €' .$priceTotal . ',- </div>';
}
else {
echo '<div class="item-price"> €' .$priceTotal . '</div>';
}
echo '</li>';
}}
endwhile;
?>
</ul>
<input type="submit" name="action" value="Bereken">
<input type="submit" name="action" value="Send">
</form>
<div class="totalprice">
<?php
// is bereken button clickied
if($_POST["action"]=="Bereken") {
(float)$total = 0;
while($products->have_posts()): $products->the_post(); {
$id = get_the_ID();
$title = get_the_title();
$permalink = get_permalink();
$price = get_post_meta(get_the_id(),'wpc_product_price',true);
$product_id = get_post_meta(get_the_id(), 'product_ID', true);
if(in_array($id, $_SESSION['cart'])){
if (is_numeric($price) && (floor($price) == $price)) {
$price = number_format($price, 2);
}
else {
$price = str_replace(',', '.', $price);
}
$total += (floatval($price) * floatval($_GET["amount$id"]));
}}
endwhile;
(String)$total;
number_format($total, 2);
$totalDecimal = str_replace('.', ',', $total);
echo 'Subtotaal: €' .$totalDecimal. '<br />';
echo 'BTW: €' . str_replace('.',',', number_format($total * 0.21,2)). '<br />';
echo 'Totaal: €' . str_replace('.',',', number_format($total * 1.21,2));
}
function changeFormat($var) {
if(is_numeric($var) && (floor($var) == $var)){
return number_format($var, 0) + ',-';
}
else {
if (is_numeric($var)) {
return number_format($var, 2, ',', '.');
}
else if (is_string ($var)){
return str_replace(',', '.', $var);
}
else {
echo "What the hell is dit voor een formaat?";
}
}}
?>
</div>
</div>
</div>
</main>

Get category from post nibbleblog script?

I want to get correct category link where post has posted!
Simple example: http://news.filmground.host-ed.me/
Look "Author: Elar", so next after that should be a category link like "Category: Game News"!
I think source code is here, taken from plugin "categories"
code is here
<?php
// =====================================================================
// PLUGIN INFO
// =====================================================================
$_PLUGIN_CONFIG['DATA'] = array(
'author'=>'Diego Najar',
'version'=>'3.6',
'url'=>'http://www.nibbleblog.com'
);
// =====================================================================
// PLUGIN CLASS
// =====================================================================
class PLUGIN_CATEGORIES extends Plugin
{
public function blog_body()
{
global $categories;
$html = '<ul>';
foreach($categories as $category)
{
// URL generator
$href = Url::category($category['slug']);
$html .= '<li class="category">'.$category['name'].'</li>';
}
$html .= '</ul>';
return $html;
}
}
?>
and page where this goes is here
<header>
<h1 class="post-title">
<?php echo Post::title() ?>
</h1>
<div class="post-published"><span style="font-size:13px"><img alt="Date when post was added!" src="img/dd.png" style="height:13px; margin-bottom:-2px; margin-top:0px; width:13px" title="Date when post was added!" /> Posted on:</span> <?php echo Post::published() ?> | <img alt="Date when post was added!" src="img/au.png" style="height:13px; margin-bottom:-2px; margin-top:0px; width:13px" title="Post author!" /> Author: Elar</div>
</header>
<div class="post-content">
<?php echo Post::content() ?>
</div>
<footer>
<span class="comment-count">
<?php echo Post::comment_count_link() ?>
</span>
<div class="post-tags"><?php echo Post::tags ()?></div>
</footer>
And also how get commas between tags?
<div class="post-tags"><?php echo Post::tags ()?></div>
I am using nibbleblog blog script!
For category try to add this to your html
<?php echo Post::category() ?>
And for tags this should work:
<?php
$tagLinks = array();
foreach (Post::tags(TRUE) as $tag) {
$tagLinks[] = '<a class="tag" href="' . Url::tag($tag['name']) . '">' . $tag['name_human'].'</a>';
}
?>
<div class="post-tags"><?php echo implode(', ', $tagLinks); ?></div>

multiple inputs - Problems with array

it is such that I need to use multiple inputs on my side,
I've tried to do like this but it does not work as it will not show up on the page at all in some manner.
HTML
<div id="onlinetestside">
<div id="onlinetestsidealt"><?php echo $ordet;?></div>
<input type="text" name="ord[]" maxlength="190">
<div style="clear:both;"></div>
</div>
PHP
//ordetalt its coming from database.
$alt = $_POST["ord"];
if($ordetalt == $alt)
{
echo $ordetalt . " og " . $alt;
}
else
{
echo "Error " . $ordetalt . " and " . $alt;
}
error appears like this:
Error Hej and Array
What I want to get to it shall be such that "$ordetalt == $alt" have the same content and it fits together.
EIDT
Here I show the entire code where I need to download some code to the side.
if ($stmt = $this->mysqli->prepare('SELECT id, ordet, ordetalt FROM test WHERE getid = ?')) {
$stmt->bind_param('i', $id);
$id = $_GET['id'];
$stmt->execute();
$stmt->bind_result($id, $ordet, $ordetalt);
while ($stmt->fetch()) {
?>
<div id="onlinetestside">
<div id="onlinetestsidealt"><?php echo $ordet;?></div>
<input type="text" name="ord[]" maxlength="190">
<div style="clear:both;"></div>
</div>
<?php
//ordetalt its coming from database
$alt = $_POST["ord"];
if($ordetalt == $alt)
{
echo $ordetalt . " og " . $alt;
}
else
{
echo "Error " . $ordetalt . " and " . $alt;
}
}
$stmt->close();
}
EIDT EIDT
$i = 0;
$a = $i++;
$alt = $_POST["ord"][$a];
if($ordetalt == $alt)
{
echo $ordetalt . " og " . $alt;
}
else
{
echo "Error " . $ordetalt . " and " . $alt;
}
Barmar is spot on, your line
$alt = $_POST["ord"];
Should read
$alt = $_POST["ord"][0];
OR
change your html like so:
<div id="onlinetestside">
<div id="onlinetestsidealt"><?php echo $ordet;?></div>
<input type="text" name="ord" maxlength="190">
<div style="clear:both;"></div>
</div>

codeigniter avoiding html div's

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>

Categories