Options to maintain line breaks in PHP > HTML source code? - php

I'd like to keep my HTML source code pretty and indented (or tabbed). For instance:
$someHTML.='<div class="NOINDENT">';
$someHTML.=' <div class="INDENT1">';
$someHTML.=' <div class="INDENT2"><div>';
$someHTML.=' </div>';
$someHTML.='</div>';
echo $someHTML;
This PHP looks pretty and readable enough to me, but when the HTML is output it will be one long line of code (with no line breaks)! I'd like to have PHP print a line break, but still have the code "readable" while working on it in PHP.
For the above example, is using \n at the end of each line my only option?

Heredoc syntax to the rescue
$someHTML = <<<HTML
<div>
<div>
...
</div>
</div>
HTML;

you can use the constant PHP_EOL to end your lines
$someHTML.='<div class="NOINDENT">'.PHP_EOL;
The HEREDOC syntax is better, but when you are inside functions / loop / etc. which requires tabs, it make the php code looks weird sometimes

I try and avoid echoing html if its more than a single line.
Instead you can use output buffering if you need the html in a string, eg if you need to return a string from a function:
function getHtmlString(){
ob_start(); ?>
<div class="NOINDENT">
<div class="INDENT1">
<div class="INDENT2"><div>
</div>
</div>
<?php
$html = ob_get_clean();
return $html;
}
?>
<html>
<head>...</head>
<body>
<div id="someid">
<?php echo getHtmlString(); ?>
...

Yes, you must add '\n' at the end.
And if you want tabs, add '\t' at the beggining of each line.

In order to use line breaks, you need to use the double-quoted string form and place a newline (\n) character at the end of every line. Note that the double quotes within the string now need to be escaped with a backslash. For example:
$someHTML.="<div class=\"NOINDENT\">\n";
$someHTML.=" <div class=\"INDENT1\">\n";
$someHTML.=" <div class=\"INDENT2\"><div>\n";
$someHTML.=" </div>\n";
$someHTML.="</div>\n";
echo $someHTML;
Another option would be to use the HEREDOC string format, which will maintain whitespace and also has the advantage of not requiring you to escape double quotes:
$someHTML = <<<HERE
<div class="NOINDENT">
<div class="INDENT1">
<div class="INDENT2"><div>
</div>
</div>
HERE;

I wanted to show that this solution is close to what I want , and works great, but the staring and ending ' and '; aren't that pretty. heredoc seems like the best and cleanest answer so far.
function html(){
$someHTML=
'<div class="NOINDENT">a
<div class="INDENT1">b
<div class="INDENT2">c<div>
</div>
</div>';
return $someHTML;
}
echo(html());

Related

What is the meaning of syntax <<<XML XML in this example "https://www.php.net/manual/en/simplexml.examples-basic.php"? [duplicate]

For example:
$sql = <<<MySQL_QUERY
That's heredoc syntax. You start a heredoc string by putting <<< plus a token of your choice, and terminate it by putting only the token (and nothing else!) on a new line. As a convenience, there is one exception: you are allowed to add a single semicolon after the end delimiter.
Example:
echo <<<HEREDOC
This is a heredoc string.
Newlines and everything else is preserved.
HEREDOC;
This is called a heredoc, and it lets you do a long piece of text that goes over several lines. You can put PHP variables in there and they will replace with the value. The word CHART can be anything. It just needs to be the same to start and stop where the quoted text begins.
You could do the same thing by appending multiple quoted strings, but this is cleaner most of the time for extended documents like this HTML text. There is also something called a nowdoc which is like a single quote string in PHP, but these won't let you use variables inside them.
It is the start of a string that uses the HEREDOC syntax.
A third way to delimit strings is the heredoc syntax: <<<.
After this operator, an identifier is provided, then a newline. The string itself follows, and then the same identifier again to close the quotation.
It's PHP's heredoc.
Example:
$sql = <<<MySQL_QUERY
SELECT *
FROM TAB
WHERE A = 1 AND B = 2
MySQL_QUERY;
It's a heredoc, for long strings that you don't have to worry about quotation marks and whatnot. If you notice the word CHART and then there's a line that says CHART;, that indicates the end of the string.
The important thing to remember when using this format is that whatever string you use to define the end of the string (such as CHART in this case), that word has to appear on a line on its own, followed by a semicolon, and NO characters can occur after the semicolon on the same line, even whitespace, otherwise PHP thinks it's part of the string.
It's the heredoc syntax.
$str = <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;
I found both Heredoc and Nowdoc extremelly powerfull and usefull in PHP and I am surprise that no one have so far give more example of what you can do.
First the difference between Heredoc and Nowdoc is simple,
Heredoc: Is like the "" double quote string you can put Variables
Nowdoc: Is like the '' single quote string no variable are parsed
For the following example I will only show the Heredoc, in order to make a Nowdoc just wrap the token inside single quotes -> 'TOKEN'.
Features and Advantages
The "" and '' can be added as much as needed and won't cause any errror
Easily output HTML code with dynamic variables, avoid usesell concatenations.
Store it in variables for letter use, can create small components and just output them.
The Lines are interpreted literally with '\n' hence is like writing in a doc, also useful to add with nl2br .
Simple Example
$a = "Hello";
$b = "World";
// HEREDOC
echo <<<HEREDOC
<strong> HEREDOC: </strong>
Variable A: "$a"
Variable B: "$b"
HEREDOC;
echo '</br>';
// NOWDOC
echo <<<'NOWDOC'
<strong> NOWDOC: </strong>
Variable A: "$a"
Variable B: "$b"
NOWDOC;
output
HEREDOC: Variable A: "Hello" Variable B: "World"
NOWDOC: Variable A: "$a" Variable B: "$b"
Recipes
Use nl2br to add <br> for each line
This works because HEREDOC interpretes each \n as an actual line
// HEREDOC
echo nl2br(<<<HEREDOC
<strong> HEREDOC: </strong>
Variable A: "$a"
Variable B: "$b"
HEREDOC);
// Output HEREDOC:
//Variable A: "Hello"
//Variable B: "World"
Create small components
<?php
foreach($tasks as $task) {
// Create an HTML like component
$component = <<<HEREDOC
<div class="pure-u-1-3">
<div class="card">
<div class="card-header">
{$task['name']}
</div>
<div class="card-body">
<h5 class="card-title"> {$task['state']} </h5>
<p class="card-text"> {$task['description']} </p>
See Task Todos
</div>
</div>
</div>
HEREDOC;
echo $component; // Output
}
?>
Or just put in one string then output with 1 echo
<?php
$taskRendered = '';
foreach($tasks as $task) {
// Create an HTML like component
$component = <<<HEREDOC
<div class="pure-u-1-3">
<div class="card">
<div class="card-header">
{$task['name']}
</div>
<div class="card-body">
<h5 class="card-title"> {$task['state']} </h5>
<p class="card-text"> {$task['description']} </p>
See Task Todos
</div>
</div>
</div>
HEREDOC;
$taskRendered .= $component;
}
echo $taskRendered; // Output
?>
Documentation
HEREDOC DOCS
NOWDOW DOCS
To get a clear idea:
$data = array(
"Id" => 12345,
"Cutomer" => "hi",
"Quantity" => 2,
"Price" => 45
);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
If we use <<<:
$data = <<<DATA
{
"Id": 12345,
"Customer": "John Smith",
"Quantity": 1,
"Price": 10.00
}
DATA;
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
Conclusion: If we go with the 1st method we have to convert it into json_encode() which somehow requires some processing. Instead, We can use the <<< operator to save some time and get some clean code. :)

Add space to every line outside PHP code block

I know exactly what I want to realize, but I dont really know how to go about it with PHP.
I have made up some code that should serve as the concept of how it should actually be.
I want to indent every new line with X amount of spaces for the code that's out of the brackets.
Is there a way to accomplish what I want?
I am not trying to do anything visual on the design, but rather have my code properly indented.
<?php
// Other PHP Code
foreach(explode("\n", $content) as $line) {
?>
This code outside the php block should be in the $content variable above to alter it.
<div class="content">
<!-- Content -->
</div>
<?php
echo str_repeat(" ", 4), $line;
}
// Other PHP Code
?>
What about using css margin? You can give the line a class like this:
html:
<div class="myClass">here is my special text</div>
css:
.myClass{
margin-left: 10px;
}
Replace echo str_repeat(" ", 4), $line;
by echo str_repeat(" ", 4), $line;
Indenting the source code itself works fine. No need for any fancy PHP code.
<?php
// Other PHP Code
foreach(explode("\n", $content) as $line) {
?>
<!--Indent here!-->
<div class="content">
<!-- Content -->
<?php echo $line; //assuming this is what you wanted to print ?>
</div>
<?php
}
// Other PHP Code
?>
Notice how the HTML part (div) is indented. PHP will keep this indentation when generating the resulting HTML code.

a problem with heredocs syntax?

I have a problem with the syntax for a heredoc. Let me show the code first:
function format($user_id,$user_note,$image,$dt){
//this is the problem
if($image=='NULL'){
//don't display image
}
else {
echo '<img src="userpics/$image" width="480" height="480">';
}
return <<<ENDOFRETURN
<div class ="commentbox">
$date
</div>
<div class="leftpanel">
$user_note
$image
<div class="date">
$rel
</div>
</div>
ENDOFRETURN;
}
The $image variable comes from the database, it's either NULL or has a filename. If an image is null I don't want to display the <img> tag, if it does have a value then I want to show it. Do you know how I can solve this problem? I have been trying everything, but nothing has worked yet!! :))
If data in a MySQL database is NULL, you would check that with the is_null() function, not comparing to the string 'NULL':
function format($user_id,$user_note,$image,$dt)
{
if(!is_null($image)){
$image = "<img src=\"userpics/$image\" width=\"480\" height=\"480\">";
}
return <<<ENDOFRETURN
<div class ="commentbox">$date</div>
<div class="leftpanel">
$user_note
$image
<div class="date">$rel</div>
</div>
ENDOFRETURN;
}
Also, as others have mentioned, the end of the heredoc must not be indented.
EDIT: I just edited a few other things in your code and showed the whole function to give you a better idea.
I can see several problems with your code, but where the heredocs syntax is concerned, try removing the spaces before ENDOFRETURN;.
There are several problems, the correct way would be something like:
function format($user_id,$user_note,$image,$dt){
//this is the problem
if($image !== NULL){
$output .= '<img src="userpics/' . $image . '" width="480" height="480">';
}
$output .= <<<ENDOFRETURN
<div class ="commentbox">
$date
</div>
<div class="leftpanel">
$user_note
$image
<div class="date">
$rel
</div>
</div>
ENDOFRETURN;
return $output;
}
you see:
ENDOFRETURN; has no spaces before it
all output is returned in one ... return
For the sake of being thorough:
NULL is a keyword, just like: print, echo, if, for. Meanwhile,'NULL' (note the quotes) is a string, just like if you had typed 'if' (note the quotes, again) it would be a string, not the beginning of an if statement.
Your echo statement in single quotes as above, won't do what you intend it to. The variable $image will not be expanded in a single-quoted string. Reverse your single and double quoting instead as
echo "<img src='userpics/$image' width='480' height='480'>";
Also the ENDOFRETURN; at closing your heredoc must not have any spaces before it.
simply adjust
{spaces or tab}ENDOFRETURN;
to
{no spaces/tab}ENDOFRETURN;
rtm - exactly same problem as yours
It is very important to note that the line with the closing identifier must contain no other characters, except possibly a semicolon (;). That means especially that the identifier may not be indented, and there may not be any spaces or tabs before or after the semicolon. It's also important to realize that the first character before the closing identifier must be a newline as defined by the local operating system. This is \n on UNIX systems, including Mac OS X. The closing delimiter (possibly followed by a semicolon) must also be followed by a newline.
If this rule is broken and the closing identifier is not "clean", it will not be considered a closing identifier, and PHP will continue looking for one. If a proper closing identifier is not found before the end of the current file, a parse error will result at the last line.

In PHP, what does "<<<" represent?

For example:
$sql = <<<MySQL_QUERY
That's heredoc syntax. You start a heredoc string by putting <<< plus a token of your choice, and terminate it by putting only the token (and nothing else!) on a new line. As a convenience, there is one exception: you are allowed to add a single semicolon after the end delimiter.
Example:
echo <<<HEREDOC
This is a heredoc string.
Newlines and everything else is preserved.
HEREDOC;
This is called a heredoc, and it lets you do a long piece of text that goes over several lines. You can put PHP variables in there and they will replace with the value. The word CHART can be anything. It just needs to be the same to start and stop where the quoted text begins.
You could do the same thing by appending multiple quoted strings, but this is cleaner most of the time for extended documents like this HTML text. There is also something called a nowdoc which is like a single quote string in PHP, but these won't let you use variables inside them.
It is the start of a string that uses the HEREDOC syntax.
A third way to delimit strings is the heredoc syntax: <<<.
After this operator, an identifier is provided, then a newline. The string itself follows, and then the same identifier again to close the quotation.
It's PHP's heredoc.
Example:
$sql = <<<MySQL_QUERY
SELECT *
FROM TAB
WHERE A = 1 AND B = 2
MySQL_QUERY;
It's a heredoc, for long strings that you don't have to worry about quotation marks and whatnot. If you notice the word CHART and then there's a line that says CHART;, that indicates the end of the string.
The important thing to remember when using this format is that whatever string you use to define the end of the string (such as CHART in this case), that word has to appear on a line on its own, followed by a semicolon, and NO characters can occur after the semicolon on the same line, even whitespace, otherwise PHP thinks it's part of the string.
It's the heredoc syntax.
$str = <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;
I found both Heredoc and Nowdoc extremelly powerfull and usefull in PHP and I am surprise that no one have so far give more example of what you can do.
First the difference between Heredoc and Nowdoc is simple,
Heredoc: Is like the "" double quote string you can put Variables
Nowdoc: Is like the '' single quote string no variable are parsed
For the following example I will only show the Heredoc, in order to make a Nowdoc just wrap the token inside single quotes -> 'TOKEN'.
Features and Advantages
The "" and '' can be added as much as needed and won't cause any errror
Easily output HTML code with dynamic variables, avoid usesell concatenations.
Store it in variables for letter use, can create small components and just output them.
The Lines are interpreted literally with '\n' hence is like writing in a doc, also useful to add with nl2br .
Simple Example
$a = "Hello";
$b = "World";
// HEREDOC
echo <<<HEREDOC
<strong> HEREDOC: </strong>
Variable A: "$a"
Variable B: "$b"
HEREDOC;
echo '</br>';
// NOWDOC
echo <<<'NOWDOC'
<strong> NOWDOC: </strong>
Variable A: "$a"
Variable B: "$b"
NOWDOC;
output
HEREDOC: Variable A: "Hello" Variable B: "World"
NOWDOC: Variable A: "$a" Variable B: "$b"
Recipes
Use nl2br to add <br> for each line
This works because HEREDOC interpretes each \n as an actual line
// HEREDOC
echo nl2br(<<<HEREDOC
<strong> HEREDOC: </strong>
Variable A: "$a"
Variable B: "$b"
HEREDOC);
// Output HEREDOC:
//Variable A: "Hello"
//Variable B: "World"
Create small components
<?php
foreach($tasks as $task) {
// Create an HTML like component
$component = <<<HEREDOC
<div class="pure-u-1-3">
<div class="card">
<div class="card-header">
{$task['name']}
</div>
<div class="card-body">
<h5 class="card-title"> {$task['state']} </h5>
<p class="card-text"> {$task['description']} </p>
See Task Todos
</div>
</div>
</div>
HEREDOC;
echo $component; // Output
}
?>
Or just put in one string then output with 1 echo
<?php
$taskRendered = '';
foreach($tasks as $task) {
// Create an HTML like component
$component = <<<HEREDOC
<div class="pure-u-1-3">
<div class="card">
<div class="card-header">
{$task['name']}
</div>
<div class="card-body">
<h5 class="card-title"> {$task['state']} </h5>
<p class="card-text"> {$task['description']} </p>
See Task Todos
</div>
</div>
</div>
HEREDOC;
$taskRendered .= $component;
}
echo $taskRendered; // Output
?>
Documentation
HEREDOC DOCS
NOWDOW DOCS
To get a clear idea:
$data = array(
"Id" => 12345,
"Cutomer" => "hi",
"Quantity" => 2,
"Price" => 45
);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
If we use <<<:
$data = <<<DATA
{
"Id": 12345,
"Customer": "John Smith",
"Quantity": 1,
"Price": 10.00
}
DATA;
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
Conclusion: If we go with the 1st method we have to convert it into json_encode() which somehow requires some processing. Instead, We can use the <<< operator to save some time and get some clean code. :)

PHP: Breaking out of PHP for HTML but return as value instead of print on page?

I am generating a lot of HTML code via PHP, but I need to store it in a variable, not display it immediately. But I want to be able to break out of PHP so my code isnt a giant string.
for example (but actual code will be much larger):
<?php
$content = '<div>
<span>text</span>
link
</div>';
?>
I want to do something like this:
<?php
$content =
?>
<div>
<span>text</span>
link
</div>
<?php
;
?>
But I know this will not return the html as a value it will just print it to the document.
But is there a way to do this tho?
Thanks!
You can use output buffering:
<?php
ob_start();
?>
<div>
<span>text</span>
link
</div>
<?php
$content = ob_get_clean();
?>
Or a slightly different method is HEREDOC syntax:
<?php
$content = <<<EOT
<div>
<span>text</span>
link
</div>
EOT;
?>
Try this:
<?php
$var = <<<EOD
my long string
EOD;
echo $var;
?>
(edit done, but one has edit faster than me :))
In my opinion, you should look into a template engine such as Smarty. It can help you take some of the ugliness out of hardcoding HTML into the PHP file, and can help make the code more manageable.
You could store the html in an html file and read that file into a variable.
While still technically a string, you might find the documentation on PHP's heredoc to be an entertaining read:
heredoc syntax
$content = <<<EOT
<div>
<span>text</span>
link
</div>
EOT;
Use heredoc syntax.

Categories