PHP Introduction
HTML output from web server
PHP can be used to add content to HTML files. While HTML is processed directly by a web browser, PHP scripts are executed by a web server and the resulting HTML is sent to the browser.
The following HTML markup contains a PHP statement that will add Hello World! to the output:
<!DOCTYPE html>
<html>
<head>
<title>PHP!</title>
</head>
<body>
<p><?php echo "Hello world!"; ?></p>
</body>
</html>
Output
echo also has a shortcut syntax, which lets you immediately print a value. Prior to PHP 5.4.0, this short syntax only works with the short_open_tag configuration setting enabled.
For example, consider the following code:
<p><?= "Hello world!" ?></p
Its output is identical to the output of the following:
<p><?php echo "Hello world!"; ?></p>
In real-world applications, all data output by PHP to an HTML page should be properly escaped to prevent XSS(Cross-site scripting) attacks or text corruption.
Hello, World!
The most widely used language construct to print output in PHP is echo:
echo "Hello, World!\n";
print "Hello, World!\n";
Both statements perform the same function, with minor differences:
- echo has a void return, whereas print returns an int with a value of 1
- echo can take multiple arguments (without parentheses only), whereas print only takes one argument
- echo is slightly faster than print
Both echo and print are language constructs, not functions. That means they do not require parentheses around their arguments. For cosmetic consistency with functions, parentheses can be included. Extensive examples of the
use of echo and print are available elsewhere.
C-style printf and related functions are available as well, as in the following example:
printf("%s\n", "Hello, World!");
Output
PHP Tags
There are three kinds of tags to denote PHP blocks in a file. The PHP parser is looking for the opening and (if present) closing tags to delimit the code to interpret.
Standard Tags
These tags are the standard method to embed PHP code in a file
<?php
echo "Hello World";
?>
Echo Tags
These tags are available in all PHP versions, and since PHP 5.4 are always enabled. In previous versions, echo tag could only be enabled in conjunction with short tags.
<?= "Hello World" ?>
Short Tags
You can disable or enable these tags with the option short_open_tag.
<?
echo "Hello World";
?>
ASP Tags
By enabling the asp_tags option, ASP-style tags can be used.
<%
echo "Hello World";
%>
These are an historic quirk and should never be used. They were removed in PHP 7.0.