How to remove whitespaces from generated HTML? - php

FUNCTIONS.PHP
<?php
function global_header($page)
{
echo "
<!doctype html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>" . $page . "</title>
<meta name='description' content='BTI320 Assignment 2' />
</head>
<body>
";
}
?>
<?php
function global_footer()
{
echo "
</body>
</html>
";
}
?>
When I view my page source in chrome/FF I get the following source:
<!doctype html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>Add</title>
<meta name='description' content='BTI320 Assignment 2' />
</head>
<body>
</body>
</html>
It's indented by about 3 tabs. Is there a PHP strip function or something that can align it properly? I don't like my entire pages HTML being messed up.
My expected output is to not be indented.

The reason you are getting indented outputs is that you are echoing them like that...
Simply remove the indentaions from the echo statements to get rid of them
<?php
function global_header($page)
{
echo "
<!doctype html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>" . $page . "</title>
<meta name='description' content='BTI320 Assignment 2' />
</head>
<body>";
}
?>
<?php
function global_footer()
{
echo "
</body>
</html>";
}
?>
This makes your php harder to follow fut the output will be as you requested

Consider using a template engine. Direct output of HTML strings is considered bad practice.
If you don't want to use third-party template engines, you can anyway benefit from some simplified templating like this:
page.tpl template file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset='utf-8' />
<title>{{title}}</title>
</head>
<body>
{{body}}
</body>
</html>
PHP:
// Loading HTML code that does not contain any undesired whitespace.
$code = file_get_contents('page.tpl');
// Replacing template variables with their values.
$code = str_replace(
array(
'{{title}}',
'{{body}}'
),
array(
'Example title',
'Page body'
),
$code
);
// Outputting resulting HTML code.
echo $code;

Related

Use PHP string at start of page, that were setted at the end of page

Is there any way to get PHP string value before it was setted. Maybe it's possible to make with substr_replace?
I need to write this code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title><?php echo $monkey;></title>
</head>
<body>
<?php
$monkey = "I like banana!";
echo $monkey;
?>
</body>
</html>
To get this result:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>I like banana!</title>
</head>
<body>
I like banana!
</body>
</html>
I know I could set $monkey before <html> code, but can I declare $monkey at the end of page to get it at the beginning?
UPDATE:
This example not working:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title><?php title();?></title> <!-- Need result I like banana! -->
</head>
<body>
<?php
$monkey = "I like banana!";
function title(){
echo "$monkey";
}
title();
?>
</body>
</html>
Here ya go! Just use a function!
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title><?php title();?></title>
</head>
<body>
<?php
function title(){
$monkey = "I like banana!";
echo $monkey;
}
title();
?>
</body>
</html>
Why not just set the variable before you start emitting the page?
<?php $monkey = "I like bananas"; ?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title><?php echo $monkey;?></title>
</head>
<body>
<?php
echo $monkey;
?>
</body>
</html>

Print html content in php function

I'm trying to create a function 'header' which will print html content (doctype, html, head, body, etc) - but when I'm looking in a site source, all of that stuff is in one line, not in a tree hirearchy...
public function header() {
print(
'<!DOCTYPE HTML>'
. '<html>'
. '<head>'
. '<meta charset="utf-8"/>'
);
And when I'm looking in the web source the output looks like:
<!DOCTYPE HTML><html><head><meta charset="utf-8"/>
I would like it to look more like standard html tree:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8"/>
How can I do that? What are the options ?
EDIT:
Some of You showed me an echo option - it works, but it looks really bad in a php file - like:
public function header() {
echo "<!DOCTYPE HTML>
<html>
<head>
<meta charset='utf-8' />
</head>
<body>
</body>
</html>
";
The most classic way, using echo :
echo '<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8"/>
';
see below methods for printing HTML inside PHP code block
FOR SHORT HTML CONTENTS
echo ' <div class="myClass"> Some Text here. Some text here </p> ';
FOR SHORT HTML CONTENTS WITH PHP variable concatenation
$myName='Optimum';
echo ' <div class="myClass"> My Name is '. $myName .' </p> ';
FOR LONG CONTENT
$html.='';
$phpVariable ='Dummy content'
$html.='<div class="wrapper">'
$html.='<div class="content">';
$html.='<p> My content here'. $phpVariable .' </p>';
$html.='</div>';
$html.='</div>';
echo $html;
According to your scenario
<?php
public function header() { // SOME NECESSARY PHP CODE ?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="<?php //echo get_chartset ?>"/>
<link rel="stylesheet" type="text/css" href="<?php //echo_css_path ?>">
}
?>
This will echo/ print clean HTML code in front.
You could introduce tabs when you print:
print("<!DOCTYPE HTML>"
. "<html>"
. "\t<head>"
. "\t\t<meta charset=\"utf-8\"/>"
);
Another approach would be to simply just separate your html template file (Format it however you want) and then just require it with passed data in your function like so
my_view.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h1><?= $heading ?></h1>
</body>
</html>
Your function
function showTemplate($view, array $data) {
extract($data);
require $view . '.php';
}
That way you can just call to output your view with data, like this
showTemplate('my_view', [ 'heading' => 'Awesome Page' ]);
This way your template and data would be more organized and pretty.
Another way, for doing this :
<?php
function myheader() {
?><!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8"/>
<?php } ?>
I redefined the function name to avoid conflict, (off-topic).
I don't know how such a code should be indented ...

Storing HTML file as a PHP string

I have a full HTML page:
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>Template</title>
<meta name="description" content="">
<meta name="HandheldFriendly" content="True">
...
</head>
<body>
...
</body>
</html>
I'm trying to save it in a variable like so:
$template = htmlentities("<!DOCTYPE HTML><html lang="en-US">...", ENT_HTML5, "UTF-8" );
.. but it chokes at just the first HTML tag.
That's because the first HTML tag has double quotes, just like you use for delimiting your string literal.
$template = <<<EOD
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>Template</title>
<meta name="description" content="">
<meta name="HandheldFriendly" content="True">
...
</head>
<body>
...
</body>
</html>
EOD;
You are not escaping the string propertly Try to:
Replace
htmlentities("//whatever your html code is//");
with
htmlentities('//whatever your html code is//');
user addslashes function..it will not truncate your string in between.
This function can be used to prepare a string for storage in a database and database queries.
Before storing into database or for any purpose
$final_string = addslashes('<!DOCTYPE HTML>
..........');
Before rendering that output on browser
$normal_string = stripslashes($database_retrived_string);
$data = '<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>Template</title>
<meta name="description" content="">
<meta name="HandheldFriendly" content="True">
...
</head>
<body>
...
</body>
</html>';
base64_encode($data);
Try this:
$temp = addslashes('<!DOCTYPE HTML><html lang="en-US">...', ENT_HTML5, "UTF-8" );
$template = htmlentities($temp);

saveHTML() not working properly

I have this line of code in my index.php:
<?php include ("header.php"); ?>
</body>
</html>
My header.php:
<!DOCTYPE html>
<html lang="en">
<head>
<?php include("php/dynamic_header.php"); ?>
<meta charset="utf-8">
<meta name="description" content="Write a description" />
<meta name="keywords" content="Your keywords here" />
<title>Random Title</title>
</head>
<body>
<header>This is my header</header>
And my dynamic_header.php:
$dom = new domDocument;
#$dom->loadHTMLFile("header.php");
$meta = $dom->getElementsByTagName('meta')->item(1);
$meta->setAttribute('content','new description');
$dom->saveHTML();
However, when I use saveHTML(), nothing happens.
I tried using:
echo $dom->saveHTML();
But this produces two headers, so can someone explain me what am I doing wrong?
Basically, I'm trying to change attribute on my meta tag with PHP DOM, but I can't save it without duplicating my header.
It should work just as good with saveHTMLFile() which is why I believed something was wrong with your file permissions or so not allowing you to save back the data. Either way, I think you're doing this wrong you should use a template library instead of modifying the data with DOMDocument.
For example with Smarty, you could do a header template like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="description" content="{$description|default:"Write a description"}" />
<meta name="keywords" content="Your keywords here" />
<title>{$title|default:"Default Page Title"}</title>
</head>
<body>
Here was the relevant test code to show it would not create duplicates with DOMDocument:
<?php
$str = <<<DATA
<!DOCTYPE html>
<html lang="en">
<head>
<?php include("php/dynamic_header.php"); ?>
<meta charset="utf-8">
<meta name="description" content="Write a description" />
<meta name="keywords" content="Your keywords here" />
<title>Random Title</title>
</head>
<body>
<header>This is my header</header>
DATA;
$dom = new domDocument;
#$dom->loadHTML($str);
$dom->formatOutput = true;
$dom->preserveWhitespace = false;
$meta = $dom->getElementsByTagName('meta')->item(1);
$meta->setAttribute('content','new description');
echo $dom->saveHTML();

embeding php in html

is it possible to embed this into html
if (empty($_POST['extras'])) {
$message .="<br /> No extras selected <br />";
} else {
foreach($_POST['extras'] as $extra)
{
$message .="<br />Extras: ".$extra."";
}
}
I would like to place the above php statement at the bottom of this html code.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Booking System</title>
<link rel="stylesheet" href="css/bs-admin.css" type="text/css" />
</head>
<body>
<noscript>
<div class="js_error">Please enable JavaScript or upgrade to better browser</div>
</noscript>
<div id="index">
<h1>Thank you for your reservation!</h1>
<p>
<h3>Your Booking is as follows:</h3>
<p>Dear <b><?php echo $custInf[0] ?></b>,
<p>You have Booked: <?php echo $eventInf[0] ?>
<p>Booking Date: <?php echo $eventInf[2] ?>
<p>Booking descriptiong: <?php echo $eventInf[1] ?>
<p>Number of machines booked: <?php echo $qty ?>
<p>Street: <?php echo $comments ?>
<p>Suburb: <?php echo $suburb ?>
<p>Postcode: <?php echo $postcode ?>
<p>Dropoff: <?php echo $dropoff ?>
<p>Duraton: <?php echo $duration ?>
If it's got php code in it then it's no more HTML.
You have to call it .php or .phtml.
PHP generates, or outputs html.
You can have pure html in .php scripts (outside the <?php ?> tags), but not the other way around (i.e. no php code in regular .html files).
If you want to add some logic (the PHP code) within it, you need to have it parsed by a webserver which will, in turn, generate html.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Booking System</title>
<link rel="stylesheet" href="css/bs-admin.css" type="text/css" />
</head>
<body>
<noscript>
<div class="js_error">Please enable JavaScript or upgrade to better browser</div>
</noscript>
<div id="index">
<h1>Thank you for your reservation!</h1>
<div>
<h3>Your Booking is as follows:</h3>
<p>Dear <b><?php echo $custInf[0]; ?></b>,</p>
<p>You have Booked: <?php echo $eventInf[0]; ?></p>
<p>Booking Date: <?php echo $eventInf[2]; ?></p>
<p>Booking descriptiong: <?php echo $eventInf[1]; ?></p>
<p>Number of machines booked: <?php echo $qty; ?></p>
<p>Street: <?php echo $comments; ?> </p>
<p>Suburb: <?php echo $suburb; ?></p>
<p>Postcode: <?php echo $postcode ?></p>
<p>Dropoff: <?php echo $dropoff; ?></p>
<p>Duraton: <?php echo $duration; ?></p>
</div>
<?php
$message = "";
if (empty($_POST['extras'])) $message .="<br /> No extras selected <br />";
else
{
foreach($_POST['extras'] as $extra)
{
$message .="<br />Extras: ".$extra;
}
}
echo $message;
?>
</div>
</body>
</html>
I think you're needing to create an empty variable $message before you could start appending "extras" to it. Then all you need to do is echo $message.
Yes you can, however that's not a good way to do it. You should go for the Model-View-Controller model. It separates the HTML code from the actual code that does processing. Many PHP Framework does this. (Though personally i find them too clunky and wrote my own)
Also, embedding HTML into PHP is bad, as again, code should be separated from the HTML by as much as possible.
Example of views and controllers (From my framework):
Controller:
class Controllers extends BaseController{
function index($args=array()){
// process data
$this->render('index', array('data1'=>$data));
}
}
View:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>My site</title>
</head>
<body>
<h1><?php echo $page->data1; // echos out $data from the view ?></h1>
</body>
</html>
This is much cleaner than your model of embedding php into the HTML and/or vice versa.
Take a look at frameworks, they are usually pretty helpful, although PHP frameworks are generally very restrictive as to what you can do.
Yes, you can do what you are asking. Make sure the extension is recognizable by the php interpreter (usually .php)
If you need to hack something up quick, this is ok. But for anything else than that, look into using some sort of templating language. This becomes an important point because you want to seperate your logic from your display for the sanity of yourself and other developers that will work on your code in the future.
edit: oh, also very important. Don't use $_POST this way without sanitizing the data. It's ripe for XSS injections.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Booking System</title>
<link rel="stylesheet" href="css/bs-admin.css" type="text/css" />
</head>
<body>
<noscript>
<div class="js_error">Please enable JavaScript or upgrade to better browser</div>
</noscript>
<div id="index">
<h1>Thank you for your reservation!</h1>
<!--- bunch of stuff omitted here -->
<?php
if (empty($_POST['extras'])) {
echo "<br /> No extras selected <br />\n";
} else {
foreach($_POST['extras'] as $extra)
{
echo "<br />Extras: ".$extra."\n";
}
}
?>

Categories