Fixing HTML spacing issues from nested PHP - php

This is something that has always bothered me about PHP and I have never found an answer. Hopefully this example will provide enough information to understand my question, as I don't know how to explain it thoroughly in words.
Here is some PHP inside of HTML, in a .php file. This type of things occurs pretty often:
<html>
<head>
<!-- whatever -->
</head>
<body>
<section id="content">
<ul class="errors">
<?php
foreach ($errors as $error)
{
?>
<li><?= $error ?></li>
<?php
}
?>
I have disregarded the end tags of the HTML and used <?= shortcuts to avoid any unnecessary text.
Now, here is what expect in the HTML output (i.e., right-click -> view source):
<html>
<head>
<!-- whatever -->
</head>
<body>
<section id="content">
<ul class="errors">
<li>Example Error</li>
However, here is the actual result:
<html>
<head>
<!-- whatever -->
</head>
<body>
<section id="content">
<ul class="errors">
<li>Example Error</li>
Why? Because the foreach loop from PHP is indented 3 tabs in, so the <li> it is generating gets an ADDITIONAL 3 tabs. The solution I have been using? Here:
<html>
<head>
<!-- whatever -->
</head>
<body>
<section id="content">
<ul class="errors">
<?php
foreach ($errors as $error)
{
?>
<li><?= $error ?></li>
<?php
}
?>
Sure, this works - but man is it ugly! It seems like I have two options: make my HTML output ugly and my code readable OR make my HTML readable and my code ugly. Why can't I have both? Is there no other way?
The best thing to do, I guess, is make the code readable and the output ugly. Who checks the source code anyway? I know this is probably the most popular reaction. Ugly HTML source code just bothers me, and I wish there was a way around it without sacrificing PHP code readability.

php code doesn't generate any indents on the page. What's generating the indent is the indent in the
<li> line</li>
What you can do is: use echo to output it
<?php
foreach ($errors as $error)
{
echo "<li>$error</li>";
}
?>
Or you could do:
<?php
foreach ($errors as $error)
{?>
<li><?=$error?></li> /(indent it in the begining as much as you want in the markup)
<?}
?>
Although, imo, you needn't worry about how the markup looks. Its not important. Indents have no effect on the output

One solution would be to use the output buffer functions in PHP to buffer all HTML output, and then post-process it to indent everything properly.
See this other question on the topic:
How to properly indent PHP/HTML mixed code?

Related

How to add meta tag's values for seo using PHP?

I am using one header file for every page which will show the HTML head(which includes meta tags and other CSS links)
Here I have used everything as dynamic as if I like in the case of canonical tags I have used $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_HOST'] and all other links to CSS are also accessible even if it can be any file from any directory.
Now I want to create a one-time title meta tag & description tags like this will be my main file looks like
<!DOCTYPE html>
<html lang="en">
<head>
<title><?php echo $page_title; ?></title>
<meta name="description" content="<?php echo $page_content; ?>" />
//Other meta tags & linking to css & js files
</head>
<body>
// Content ........
</body>
</html>
Now here is the twist is that many people will say that just use
$page_title = "Here is the title of the specific page";
$page_content = "Here goes the long-form description describing the page of specific page";
Yes, this would have worked out if the pages were different and had the same place to put that all before including the header file.
But my index page looks like this let me explain it too. (Using Bulma as a framework)
<?php
require 'include/db_connect.php';
require 'include/header.php';
?>
<form name="submitform" method="POST">
<div class="columns is-multiline" id="wrapper">
<div class="column is-6-desktop is-12-tablet" id="main_content">
<div class="box">
<?php
if($country)
{
?>
<?php require 'inc/country.php'; ?>
<?php
}
else if($country && $state)
{
?>
<?php require 'inc/country_state.php' ?>
<?php
}
else if($country && $state && $district)
{
?>
<?php require 'inc/country_state_district.php'; ?>
<?php
}
else
{
?>
<?php require 'inc/other_than.php'; ?>
<?php
}
?>
</div>
</div>
</div>
</form>
<?php require 'footer.php'; ?>
</body>
</html>
The main point here is that I am using the dropdown button which gets auto-submitted using js that's not relevant here but from the top, I have just explained what is the structure of my code.
Now as you can see the if-else structure which includes other files that create dynamic pages but their code starts only from the body and not from the head directly so I am not able to add those title tags and descriptions.
Now how to add title & description tags uniquely to each of these pages.
Any solutions, please... Thanks in Advance
Like already written in the comments. You should define the vars ahead of require 'include/header.php'; or use an MVC structure.
If you still want to stay with the existing code ob_get_contents() might help you.
Use ob_start(); at the beginning to tell PHP to not print any output and instead write the output to a buffer.
You can then at a later point use ob_get_contents(); to fetch the output buffer and print it.
You have to search in the output buffer for an identifier like %page_title% then and replace it with the actual value before sending the output.
This may look like following:
echo str_replace(%page_title%, $page_title, ob_get_contents());
Still I'd rather suggest restructuring your code, as the solution with output buffer is slower, uses more memory and is poor to debug.

In php how to call or link another php page?

I am a beginner for this language and I don't know how to call another page or link
in other page please help how?
You can combine PHP and HTML together.
If you need a hyperlink in your page, you can either echo the html tags or embed the PHP code inside the HTML
Below is an example how I embedded the PHP inside the HTML tags
<html>
<head>
<title>Home</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body style="width:1250px;">
<div>
<ul>
<li>Home</li>
<?php if (isset($_SESSION['user'])) { ?>
<li>
<li class="dropdown">
Account
<div class="dropdown-content">
Profile
My Articles
</div>
</li>
</li>
<li style="float:right">Logout</li>';
<?php } else { ?>
<li style="float:right">Register</li>
<li style="float:right">Login</li>';
<?php } ?>
</ul>
</div>
</body>
And below is the example of how to use html tags inside the PHP code:
<?php
echo "<html>";
echo "<title>HTML with PHP</title>";
echo "<b>My Example</b>";
print "<i>Print works too!</i>";
?>
For page redirects, you can use the below code in your PHP :
header('location: targetfile.php');
The PHP code located after the header() will be interpreted by the server, even if the visitor moves to the address specified in the redirection. In most cases, this means that you need a method to follow the header() function of the exit() function in order to decrease the load of the server:
<?php header('Location: /directory/mypage.php'); ?>
A basic link is created by wrapping the text (or other content, see Block level links) you want to turn into a link inside an element, and giving it an href attribute (also known as a Hypertext Reference , or target) that will contain the web address you want the link to point to

A different angle on How to write html code inside php?

We write PHP code inside the HTML code via <?php ... ?> tags. So normally it would not make sense to write HTML code inside PHP code that is already inside HTML code, if you can just exit the PHP for the lines you need. But what if you need the HTML code in the same line as you have the PHP code?
My example would go like this:
<div>
<?php ($bool) ? <script>...</script> : <script></script> ?>
</div>
Is this:
<div>
<?php if($bool): ?>
<script>...</script>
<?php else: ?>
<script>...</script>
<?php endif; ?>
</div>
the only way?
Note: instead of <script> you could have <h1>, <strong>, <title> or any other "one-liner".
Thank you in advance.
Sure, alternative syntax would be the way to go when you have multiple lines of HTML, as you already stated...
However, for one liners, you can shorten <?php echo '...' ?> with <?= '...' ?> and wrap your HTML within single or double quotes, depending if you are already using double quotes within your HTML syntax. You may also escape them if you like, but that'd be messy.
<div>
<?= ($bool) ? "<script>...</script>" : "<script></script>" ?>
</div>
In order to print any string into your html code from PHP snippets use echo function.
http://php.net/manual/en/function.echo.php
So you just need to add echo
<div>
<?php
if($bool) {
echo '<script>...</script>';
} else {
echo '<script>...</script>';
} ?>
Stumbled upon this and decided to answer my own question just to point other newbies in the right direction.
Important note: Nowadays I'm using Laravel Framework and if you don't know it, you should definitely get to know it (there are alternatives though).
But I started following MVC architecture strongly even before that. So even before Laravel's Blade templates, my views looked something like the following.
<html>
<body>
<?php if ($isUserAuthenticated) : ?>
<div>
<span>Welcome <?= $username ?>
</div>
<?php else : ?>
Login
<?php endif ?>
</body>
</html>
As you can see there is absolutely no data manipulation in the view.
I also tried my best not to store any HTML strings into variables, but sometimes it makes for less code, so I did something like the following.
$alert = match($errorCode) {
1 => <<<HTML
<div class="alert alert-danger">Big error</div>
HTML,
2 => <<<HTML
<div class="alert alert-warning">Small error</div>
HTML,
default => ""
};
That way I can keep syntax highlighting (in VSCode) for HTML.
Note: match expression is new in PHP8, but you could achieve the same before with a switch statement.

HTML is still reading php code with <!---->

I have the following problem. I used the following code in my page to ignore some php code, but it seems that over the Thanksgiving weekend there was an update and it is no longer ignoring the code.
<!--
<div class="main">
<div class="main-sub">
<?php include('http://www.contractorsintelligence.com/contractors-license/includes-page-elements/navigation1.php');
?>
<div id="mid-top"><img src="" width="990" height="20" alt="Top Spacer"/></div>
<div id="mid_shdw">
-->
The rest of the html code is being ignored, but only php code is not being ignored. I know one of the ways is to include <!-- into the php function. But is there any other way to ignore the php code with the rest of the html code?
This is an HTML comment. It has no effect on the PHP code.
You should use PHP comments:
Block comment:
/*
BLOCK OF COMMENTED CODE
*/
Line comment:
// this is a commented line
The PHP code is interpreted by the server and is calculated "long" before it gets to the users browser. The HTML markup while still on the server, is just text. Only when the HTML arrives at the users browser does it get rendered (or ignored!). So your HTML comments did not matter to the server - it saw PHP code and ran it - the PHP interpreter is not programmed to recognize these strange <!-- symbols that you are giving it. ;)
Your PHP code will always be executed because it doesn't know about your HTML code that surrounds it.
The solution, if you your PHP code not to execute is to comment it out:
<!--
<div class="main">
<div class="main-sub">
<?
// php include('http://www.contractorsintelligence.com/contractors-license/includes-
// page-elements/navigation1.php');
?>
<div id="mid-top"><img src="" width="990" height="20" alt="Top Spacer"/></div>
<div id="mid_shdw">
-->
<?php /* comments */ ?>
The PHP is executed before the HTML is processed client-side.
If you want to ignore the PHP code, its your best bet to do it like this:
<?php
/* include('http://www.contractorsintelligence.com/contractors-license/includes-page-elements/navigation1.php'); */
?>
Whereas /* starts a comment and */ ends it.
PHP will parse the page before it is sent to the client (or browser). Therefore PHP is not 'interested' in <!-- or --> at all.
On the other hand, if the HTML code that is being included by your call to include() contains further HTML commentary (<!-- or -->) it may close your ignored code before the point you intended it to.
UPDATE
Your overall approach is a bit fuzzy. See here, if you want to use PHP to decide whether to show certain HTML code or not, you don't want to use HTML comments to accomplish that.
Try this instead:
<?php
if($result["r_approved"] != "APPROVED"){
?>
<div class="main">
<div class="main-sub">
<?php
include('http://www.contractorsintelligence.com/contractors-license/includes-page-elements/navigation1.php');
?>
</div>
<div id="mid-top">
<img src="https://www.contractorsintelligence.com/images/shadowbg-top.png" width="990" height="20" alt="Top Spacer"/>
</div>
<div id="mid_shdw"></div>
</div>
<?php
}
?>
You php page is executed and everything between <? ?> is executed. Php doesn't care about <!-- --> or any other tag except <? or <?php .
Then the browser doesn't display/load what is inside <!-- -->.
If you want to comment php, use // or /* ... */
<?php /* include('http://www.contractorsintelligence.com/contractors-license/includes-page-elements/navigation1.php'); */ ?>
Two things are happening at once which I think might be confusing:
Unless you wrap everything inside the php tags with /* */ or use // that code will be executed because it comes from the server.
The browser is the only one that parses the <!-- -->.
So your server is parsing the php and then the browser is hiding what was parsed.
Solution
<?php // include('http://www.contractorsintelligence.com/contractors-license/includes-page-elements/navigation1.php'); ?>
Thats because the <!-- isn't parsed by PHP, only by the browser. The easiest (but not always best readable) solution is
<?php if (false) { ?>
<b>This html will not be sent to browser</b>
<?php include('this will not be included'); ?>
<?php } // endif ?>

Cheap php templating with vprintf?

Ok,
so printf/sprint/vprintf all accept a certain type specifier syntax %[num][type]. (http://us2.php.net/sprintf see examples 3 and 4) Where num is the index to the type.
Example:
vprintf('Number %1$d string %2$s. String %2$s, number %1$d',array(1,"no"));
Yes, it is limited... And you would need to maintain the indexes. But it's native to the language and (i think) fast.
I just want some thoughts on how useful this would be as say a second stage to something like this: http://www.techfounder.net/2008/11/18/oo-php-templating/.
(and if anyone knows about printf/vprintf's speed that would be appreciated)
full example of what i'm talking about:
frontpage.php:
<html>
<head>
<title> %1$s </title>
</head>
<body>
Hello %2$s! You have reached page: %1$s!
</body>
</html>
whatever.php:
ob_start();
include frontpage.php;
$ob_output = ob_get_clean();
vprintf($ob_output,"Page Title","Bob");
If you want cheap PHP templating, use separate files with PHP expression blocks. It is possible to make a templating system using printf-style format strings, but there are two main problems I can see with this approach: speed and readability. The printf functions are intended for use on shorter strings, and although I don't have any statistics on hand, I think it's safe to say that running a sprintf() or a vprintf() on one huge string representing the page body will be slower than just using PHP expression blocks in a file.
That leads into the next issue: readability. Compare these two HTML templates:
<html>
<head>
<title>%s</title>
</head>
<body>
<div id="main">
<h1>%s</h1>
<p>%s</p>
</div>
<div id="other">
<p>%s</p>
</div>
<p id="footer">
%s. Took %.2f seconds to generate.
</p>
</body>
</html>
and
<html>
<head>
<title><?= $title ?></title>
</head>
<body>
<div id="main">
<h1><?= $header ?></h1>
<p><?= $body_text ?></p>
</div>
<div id="other">
<p><?= $misc_info ?></p>
</div>
<p id="footer">
<?= $copyright ?>. Took <?= $load_time ?> seconds to generate.
</p>
</body>
</html>
Or, let's say I had decided to use format strings with indexed arguments. Say, something like this:
<h1>%1$s</h1>
<p>%2$s</p>
<span id="blah">%3$s</p>
<p>%4$s</p>
<p>%5$s</p>
Now, what if I wanted to switch the ordering around?
<h1>%1$s</h1>
<p>%3$s</p>
<span id="blah">%5$s</p>
<p>%4$s</p>
<p>%2$s</p>
These are obviously contrived, but think about how it would be to maintain the printf templates in the long run.
So, in general, if you want quick-and-dirty PHP templating, use template files that contain PHP expression blocks. The printf functions are a lot better at tackling smaller string formatting tasks.
I generally have two files:
A controller of some sort (recipes.controller.php rewritten to /recipes/123)
One of many views for a controller (recipes.view.html)
I simply do all of the logic/database work within the controller and then include the appropriate view at the end. The view has access to all of the variables in the controller so I already have things like $title, $ingredients[], etc. created. I'm not really sure why people make it any more complicated than that. It's very easy to follow.
The view file will basically just look like this:
<html>
<head>
<title><?=$title ?></title>
</head>
etc...
Rasmus Lerdorf, creator of PHP, prefers to include his variables something like this:
<select class="f" name="cat" id="f_cat" size="1">
<option selected>Category</option>
<?php foreach($categories as $cat) echo <<<EOB
<option value="{$cat}">{$cat}</option>
EOB;
?>
For reference, <<<EOB through EOB; is a heredoc.
Source: The no-framework PHP MVC Framework by Rasmus Lerdorf

Categories