PHP include() function
This function is used to copy all the contents of a file called within the function, text wise into a file from which it is called. This happens before the server executes the code.
Syntax:
include 'php filename';
Example 1: Consider a PHP file name ‘natural.php’ which contains the following code.
<?php
$i = 1;
echo "the first 10 natural numbers are:";
for($i = 1; $i <= 10; $i++) {
echo $i;
}
?>
Output:
Example: Insert the above code into an HTML document by using the include keyword, as shown below.
<!DOCTYPE html>
<html>
<head>
<title>inserting PHP code into html</title>
</head>
<body>
<h2>Natural numbers</h2>
<?php include 'natural.php'?>
</body>
</html>
How to insert PHP code in HTML document using include or require keyword ?
Inserting PHP code in an HTML document involves embedding PHP scripts within HTML files. This is done using PHP tags (`<?php … ?>`). Common methods include using include or require statements to incorporate external PHP files, allowing dynamic content within the HTML structure.
We can insert any PHP file into the HTML code by using two keywords that are ‘Include’ and ‘Require’.
Table of Content
- PHP include() function
- PHP require() function
- Difference between the include() function & require() function