php

Use of Heredoc in PHP

Heredoc is one of the ways to store or print a block of text in PHP. The data stored in the heredoc variable is more readable and error-free than other variables for using indentation and newline. How the heredoc content can be stored in a variable or printed has shown in this tutorial.

Defining the heredoc document

The following steps need to follow to store or print the heredoc document.

  1. ‘<<<’ is used to start the heredoc document.
  2. A delimiter is required to use after ‘<<<‘ to define the starting of the document and the same delimiter name with a semicolon(;) is used at the end of the heredoc document to define the end of the document.

Example 1: Printing heredoc content

The following example shows the uses of two heredoc documents. Create a PHP file with the following script. In the script, a long text is printed using a heredoc document. The newline used in the first heredoc content does not generate a newline in the browser. , <pre> tag is used with the second heredoc document to print the heredoc content as defined in the editor.

<?php
//Print the first heredoc document
print <<< HERE
PHP is a general-purpose scripting language especially suited to web development.
It was created by Danish-Canadian programmer Rasmus Lerdorf in 1994.
The PHP reference implementation is now produced by The PHP Group.
HERE
;
//Print the second heredoc document
print <<< DOC
<pre>
www.google.com
www.bing.com
www.ask.com
www.yahoo.coms
</pre>
DOC
;
?>

Output:

The following output will appear after running the above script from the server.

Example 2: Using heredoc content in a variable

The following example shows how the heredoc content can be stored in a variable and print with other variables. Create a PHP file with the following script. $name and $phone variables are used here to store string values. $address variable is used to store heredoc content. Next, these three variables are printed by combining them.

<?php
//Define a string variable
$name = 'Carol J. Stephens';
//Define a heredoc variable
$address = <<< addr
<pre>
    1635, Franklin Street Montgomery,
    AL 36104.
</pre>
addr
;
//Define another string variable
$phone = '126-632-2345';
//Print the variables
echo "Name : <br/> <pre>   $name </pre>". "Address : $address". "Phone : <pre>    
$phone</pre>"
;
?>

Output:

The following output will appear after running the above script from the server. The contents of the variables are printed as defined in the script for using the <pre> tag.

Example 3: Displaying HTML form using heredoc variable

The following example shows how the HTML form can be defined in a variable by using the heredoc document. Create a PHP file with the following script.  A login form is designed using a heredoc document and stored in the variable, $form. The $form is printed to display the login form. Next, the PHP script will check the username and password are valid or invalid. The script will print the success message for valid entry and the error message for invalid entry.

<?php
//Define the login form
$form = <<< HTML
    <form action="#" method="post">
        <input type="text" name="username" /><br/> <br/>
        <input type="password" name="password" /><br/> <br/>
        <input type="submit" name="submit" value="Submit" />
    </form>
html
;

echo "<h3>Login Form</h3>";
//Display the login form
echo $form;
//Check the submit button is clicked or not
if(isset($_POST['submit']))
{
        //Check the validity og the user
        if($_POST['username'] == 'admin' && $_POST['password'] == 'secret'){
            echo "Authenticated user";
        }
        else{
            echo "Username or password is wrong.";
        }
}
?>

Output:

The HTML form will display after running the script from the server. The output shows the error message, ‘Username or password is wrong’ for the invalid entry.

If the user types admin as username and secret as password the script will print the success message. The following output shows the success message, ‘Authenticated user’ for typing the valid username and password.

Example 4: Using the variable inside the heredoc content

The following example shows how any variable can be used inside the heredoc content. Create a PHP file with the following script. A variable named $website is initialized with a string value that is used inside the heredoc content in the script. Next, the heredoc variable, $var is printed with formatting.

<?php
//Declare a variable with string value
$website = 'LinuxHint';
//Use variable in the heredoc content
$var = <<<here
$website is a popular blog site.
here
;
//Print the heredoc variable
echo "<h2 style='color:blue'>". $var ."</h2>";
?>

Output:

The following output will appear after running the above script from the server.

Example 5: Using heredoc variable inside the function

The following example shows how the argument values of a function can be used in a heredoc content. Create a PHP file with the following script. Here, the user-defined function named display() will take two values by two argument variables when it will call and these variables will be used inside the heredoc content. The function is called with two string values at the end of the script.

<?php
//Define a user-defined function
function display($book,$author)
{
    //Use the argument values inside the heredoc content
    print <<<book
<pre>
    Book Name: $book <br/>
    Author Name: $author <br/>
    Publisher: O'Reilly
</pre>
book
;
}
//Call the function
display("Head First PHP & MySQL","Lynn Beighley and Micheal Morrison");
?>

Output:

The following output will appear after running the above script from the server. “Head First PHP & MySQL” is passed in the first argument and “Lynn Beighley and Micheal Morrison” is passed in the second argument of the display() function. The output shows the formatted heredoc content with the values of the argument values.

Conclusion

heredoc is a good feature of PHP for storing and printing long text with any HTML tag or other variables. newdoc is another feature of PHP like heredoc that released after PHP version 5. This tutorial shows the different uses of heredoc documents in PHP by using simple examples to help the readers to know the way of using heredoc in PHP script.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.