In PHP programming, a technique for efficiently handling long strings or code spanning multiple lines is using Heredoc with EOM (End Of Document). This article will focus on this very useful method, explaining its specific usage along with the benefits during coding. This article is over 2200 characters long and SEO-friendly.
Basic of Heredoc
PHP provides a syntax called Heredoc for handling multi-line strings. Here, I will explain how to assign CSS code to a PHP variable using Heredoc with a specific code example.
<style type="text/css">
<!--
body{
...
}
...
-->
</style>
This kind of CSS code, when used for site design and layout, has the advantage of being intuitive and easy to change. Additionally, the above code can be assigned to a PHP variable and reused as a single unit.
Implementation of PHP using EOM and Heredoc
The following code is an example of using Heredoc and EOM to assign multi-line HTML code to a PHP variable and output it.
<?php
$str_work = <<< EOM
<h2>The information inside End Of Document starts here↓↓↓</h2>
<ul>
<li><a href="/css/255">Masking jpg images with CSS and png images</a></li>
<li><a href="/javascript/252">How to clear the default text (VALU value) in a textbox on input</a></li>
<li><a href="/javascript/250">FlipboardPageLayout: A Js that introduces page flipping</a></li>
<li><a href="/javascript/248">jquery.quicksand: A js that animates and sorts li tag content</a></li>
<li><a href="/php/241">How to switch between smartphone and PC sites using PHP setcookie</a></li>
</ul>
<h3>The information inside End Of Document ends here↑↑↑</h3>
EOM;
print $str_work;
?>
The value assigned to the $str_work variable is output as HTML and can be used on the web page. The benefit here is that by consolidating multi-line HTML code into one variable, code readability and maintainability are improved.
PHP Demo Page Using EOM to Assign and Output Multi-line Heredoc
As an example of using Heredoc, you can view a demo on an actual web page from the link below.
PHP Demo Using EOM to Assign and Output Multi-line Heredoc
Here, you don’t have to output each line with print or echo, which significantly reduces coding effort.
Benefits of Coding
By handling multi-line code with Heredoc, you can improve the clarity of the source code and manage long codes such as HTML, CSS, and SQL as a single unit. This enables consistent coding, making it easier to find errors and debug.
Using PHP’s Heredoc and EOM improves coding efficiency, allowing you to handle multi-line strings and code smartly.
* Please use it at your own risk.
Do not reuse the Google Analytics tag in the demo page tag.