Skip to main content

PHP: Send Text To The Browser

So we are now up and running. Now we can start getting into the actual coding. This guide page will walk you through some of the methods for sending text, via PHP, to the web browser. You may be wondering why you would want to send text to the browser using PHP when you can just type it in (X)HTML? Easy, (X) HTML isn't dynamic. By using PHP to output text to the screen you are allowing for multiple strings of text to potentially be seen by the user.

What if you wanted to show a message to logged in users, but not everyday visitors? Using PHP allows you to create a piece of code that can check to see if the user is logged in and show the appropriate text to them. By using (X)HTML to show text, you are "hard-coding" the text so that it can't be changed easily.

Echo vs Print

There are two popular methods to send text to the browser; The echo or print functions (technically they are called a language construct, but that is irrelevant for this guides usage). The main difference between them is print returns a value similar to other PHP functions.

For this guide, I will be using the echo function to output text to the browser. Anytime you see echo you can replace it with print, and 99.9999% of the time the output will be the same.

Sending Plain Text To The Browser

In order to send text to the browser we need to use:

<?php 
echo "Hello World!"; 
?>

Sending HTML To The Browser

We can also send HTML tags to the browser as well as the regular text:

<?php 
echo "<b>Hello World!</b>"; 
?>

Sending HTML With A Newline

If you are "echoing" a whole paragraph of HTML text surrounded by <p> tags, you will want to add a newline (\n) at the end so you create a line break in the HTML page source. We can do this by typing:

<?php 
echo "<p>A whole lot of text, that keeps on going and going and....</p>\n"; 
?>

This will cause PHP to output the paragraph then make a line break in the page source. It's the equivient to pressing ENTER to start a new line in text editor.

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <p><b><i><pre><a><img><em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd><h1><h2><h3><h4><h5><h6>
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.

More information about formatting options

Premium Drupal Themes by Adaptivethemes