Unit - 4
Unit - 4
What is PHP?
PHP is an acronym for "PHP: Hypertext Preprocessor"
PHP is a widely-used, open source server-side scripting language for
creating dynamic web pages.
PHP scripts are executed on the server.
PHP is platform independent and free to download and use.
HISTORY:
PHP was created by Rasmus Lerdorf to track users at his website.
In 1995, Lerdorf released it as a package called the “Personal Home Page
Tools”.
Two years later, PHP 2 features built-in database support and form
handling.
In 1997, PHP 3 was released with a rewritten parser, which substantially
increased performance and led to an explosion of PHP use.
The release of PHP 4 featured the new “Zend Engine” from Zend, a PHP
software company. This version was faster and more powerful than its
predecessor.
Currently, PHP 5 features the new “Zend Engine 2” which provides further
speed increases, exception handling and a new object-oriented
programming model.
FEATURES OF PHP:
1. PHP can generate dynamic page content.
2. PHP can create, open, read, write, delete, and close files on the server.
3. PHP can collect form data.
4. PHP can send and receive cookies.
5. PHP can add, delete, and modify data in your database.
1
6. PHP can be used to control user-access.
7. PHP can encrypt data.
8. With PHP you are not limited to output HTML. You can output images,
PDF files, and even Flash movies.
9. You can also output any text, such as XHTML and XML.
ADVANTAGES OF PHP:
Portability (Platform Independent) - PHP runs on various platforms
(Windows, Linux, UNIX, Mac OS X, etc.)
Performance - Scripts written in PHP executives faster than those written
in other scripting language.
Ease Of Use – It is easy to use. Its syntax is clear and consistent.
Open Source - PHP is an open source project –it may be used without
payment of licensing fees or investments in expensive hardware or
software. This reduces software development costs without affecting either
flexibility or reliability
PHP is compatible with almost all servers used today (Apache, IIS, etc.)
PHP supports a wide range of databases.
PHP is easy to learn and runs efficiently on the server side.
Community Support - One of the nice things about a community-supported
language like PHP is, accessing it offers to the creativity and imagination of
hundreds of developers across the world.
INSTALLING PHP:
To program PHP, follow the below three steps:
o install a web server (Any Web server capable of executing PHP codes)
o install PHP
o install a database, such as MySQL
The official PHP website (PHP.net) has installation instructions for PHP:
http://php.net/manual/en/install.php
2
"echo" – statement used to output the text on a web page:
<!DOCTYPE html>
<html>
<body>
<?php
echo "Hello World!";
?>
</body>
</html>
COMMENTS IN PHP:
A comment in PHP code is a line that is not read/executed as part of the
program. Its only purpose is to be read by someone who is looking at the
code.
Comments can be used to:
Let others understand what you are doing
Remind yourself of what you did.
Example:
<!DOCTYPE html>
<html>
<body>
<?php
// This is a single-line comment
# This is also a single-line comment
/*
This is a multiple-lines comment block that
spans over Multiple lines
*/
$x = 5 /* + 15 */ + 5;
3
echo $x;
?>
</body>
</html>
<?php
// all the echo statements are treated as same
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
</body>
</html>
Hello World!
Hello World!
Hello World!
My car is red
My house is
My boat is
4
4.1.3: PHP – VARIABLES
Declaring PHP variables: In PHP, a variable starts with the $ sign, followed by
the name of the variable.
Syntax: $variable_name
Initializing PHP variables: Variables are assigned with the = operator, with the
variable on the left-hand side and the expression to be evaluated or value on the
right. The value of a variable is the value of its most recent assignment.
Syntax: $variable_name= expression or value;
Example:
<html>
<head>
<title>Online PHP Script Execution</title>
</head>
<body>
<?php
$number = 10;
$text ="My variable contains the value of ";
print($text.$number);
?>
</body>
</html>
Output:
Global Scope:
A variable declared outside a function has a GLOBAL SCOPE and can only
be accessed outside a function:
Local Scope:
A variable declared within a function has a LOCAL SCOPE and can only be
accessed within that function.
Example:
<?php
$num1=1; // global variable
$x = 5; // global variable
$y = 10; // global variable
function myTest() {
$num1=11; // local variable
static $z=0;
$z++;
echo "z = ".$z."<br>"; // static variable retains the last changed value
global $x, $y;
$y = $x + $y;
echo "num1 inside function = ".$num1."<br>"; // prints 11
}
myTest();
mytest();
echo "x + y = ".$y."<br>"; // outputs 15
echo "num1 outside function= ".$num1; // prints 1
?>
z=1
num1 inside function = 11
z=2
num1 inside function = 11
x + y = 20
num1 outside function= 1
function myTest() {
$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
}
myTest();
echo $y; // outputs 15
?>
7
o echo can take multiple parameters (although such usage is rare)
while print can take one argument.
o echo is marginally faster than print.
The echo statement can be used with or without parentheses: echo or
echo().
The print statement can be used with or without parentheses: print or
print().
Example:
<?php
$txt1 = "Learn PHP";
$txt2 = "deitel.com";
$x = 5;
$y = 4;
echo "<h2>$txt1</h2>";
print "Study PHP at " . $txt2 . "<br>";
Output:
Learn PHP
Study PHP at deitel.com
X+Y=9
Variables can store data of different types, and different data types can do
different things.
Type Description
string Text enclosed in either single („ „) or double (“ “) quotes.
int, Integer Whole numbers (i.e., numbers without a decimal point)
float, double, real Real numbers (i.e., numbers containing a decimal point)
bool, boolean True or False
array Group of elements
8
object Group of associated data and methods
NULL No value
resource An external source – usually information from a database
PHP String:
A string is a sequence of characters, like "Hello world!".
A string can be any text inside quotes. You can use single or double
quotes.
Example: $str1=”Hello World”; $str2=‟Hello World‟;
PHP Integer:
An integer is a whole number (without decimals).
It is a number between -2,147,483,648 and +2,147,483,647.
Rules for integers:
An integer must have at least one digit (0-9)
An integer cannot contain comma or blanks
An integer must not have a decimal point
An integer can be either positive or negative
Integers can be specified in three formats: decimal (10-based),
hexadecimal (16-based - prefixed with 0x) or octal (8-based - prefixed
with 0)
Example: $x=5;
PHP Float:
A float (floating point number) is a number with a decimal point or a
number in exponential form.
Example: $x=41.45;
The PHP var_dump() function returns the data type and value.
PHP Boolean:
A Boolean represents two possible states: TRUE or FALSE.
$x = true;
$y = false;
Booleans are often used in conditional testing.
PHP Array:
An array stores multiple values in one single variable.
Example: $cars = array("Volvo","BMW","Toyota");
PHP Object:
An object is a data type which stores data and information on how to
process that data.
9
In PHP, an object must be explicitly declared.
First we must declare a class of object. For this, we use the class keyword.
A class is a structure that can contain properties and methods:
PHP Resource:
The special resource type is not an actual data type.
It is the storing of a reference to functions and resources external to PHP.
A common example of using the resource data type is a database call.
<!DOCTYPE html>
<html>
<body>
<?php
$x = 5985; // Integer variable
$y = 59.85; // float variable
$str1="Hello "; // string
$str2="World"; // string
$bool1=true; // boolean
$bool2=false; // boolean
$cars = array("Volvo","BMW","Toyota"); // array
<?php
10
// create an object
$herbie = new Car(); // creating object for car class
Output:
Example:
<!DOCTYPE html>
<html>
<body>
<?php
$var1="114";
$var2=114.12;
$var3=114;
settype($var1,"double");
settype($var2,"integer");
settype($var3,"string");
?>
</body>
</html>
12
4.1.5: PHP – CONSTANTS
A constant is an identifier (name) for a simple value. The value cannot be
changed during the script. Constants are like variables except that once
they are defined they cannot be changed or undefined.
A valid constant name starts with a letter or underscore (no $ sign before
the constant name).
CREATING CONSTANTS:
o To create a constant, use the define() function.
o Syntax:
define (name, value, case-insensitive)
Parameters:
o name: Specifies the name of the constant
o value: Specifies the value of the constant
o Case-insensitive: Specifies whether the constant name should be
case-insensitive. Default is false.
Note: Unlike variables, constants are automatically global across the entire
script. The example below uses a constant inside a function, even if it is
defined outside the function.
Example:
<html>
<head><title>Logical Operators</title><head>
<body>
<?php
define("GREETING", "Welcome to php!");
function test()
{
13
echo constant("GREETING"); echo "<br/><br/>";
define("TUTORIALS", "www.deitel.com",true);
echo "Learn PHP from <font color='blue'>".tutorials."</font>"; // no $
sign for constants
}
test();
?>
</body>
</html>
14
PHP Arithmetic Operators
The PHP arithmetic operators are used with numeric values to perform
common arithmetical operations, such as addition, subtraction,
multiplication etc.
Operator Name Example Result
+ Addition $x + $y Sum of $x and $y
- Subtraction $x - $y Difference of $x and $y
* Multiplication $x * $y Product of $x and $y
/ Division $x / $y Quotient of $x and $y
% Modulus $x % $y Remainder of $x divided by $y
Result of raising $x to the $y'th
** Exponentiation $x ** $y
power (Introduced in PHP 5.6)
15
PHP Increment / Decrement Operators
The PHP increment operators are used to increment a variable's value.
The PHP decrement operators are used to decrement a variable's value.
Operator Name Description
++$x Pre-increment Increments $x by one, then returns $x
$x++ Post-increment Returns $x, then increments $x by one
--$x Pre-decrement Decrements $x by one, then returns $x
$x-- Post-decrement Returns $x, then decrements $x by one
Example:
<html>
<head><title>Logical Operators</title><head>
16
<body>
<?php
$x=10;
$y=5;
?>
</body>
</html>
Output:
Arithmetic Operators
Add = 10+5 = 15
17
Sub = 10-5 = 5
Mul = 10*5 = 50
Div = 10/5 = 2
Assignment Operators
Add = 15
Sub = 10
Mul = 50
Div = 10
Increment / Decrement Operators
Pre-Increment = 11
Post - Increment = 11
After Increment = 12
Relational Operators
bool(false) => 12<5
bool(true) => 12>5
bool(false) => 12<=5
bool(true) => 12>=5
bool(true) => 12!=5
Logical Operators
bool(true) => 12&&5
bool(true) => 12||5
bool(false) => 12 xor 5
1. CONDITIONAL STATEMENTS:
Conditional statements are used to perform different actions based on
different conditions.
Very often when you write code, you want to perform different actions for
different decisions. We can use conditional statements in our code to do
this.
In PHP we have the following conditional statements:
if statement - executes some code only if a specified condition is true
if...else statement - executes some code if a condition is true and another
code if the condition is false
if...elseif....else statement - specifies a new condition to test, if the first
condition is false
switch statement - selects one of many blocks of code to be executed
18
1. if Statement
The if statement is used to execute some code only if a specified condition is
true.
Syntax:
if (condition) {
code to be executed if condition is true;
}
Example:
<?php
Output:
$t = date("H");
Good Morning!
if ($t < "12") {
echo "Good Morning!";
}
?>
2. if...else Statement
Use the if....else statement to execute some code if a condition is true and
another code if the condition is false.
Syntax
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
The example below will output "Have a good day!" if the current time is less than
20, and "Have a good night!" otherwise:
<?php
$t = date("H");
Output:
19
3. if...elseif.... else Statement
Use the if....elseif...else statement to specify a new condition to test, if the first
condition is false.
Syntax
if (condition) {
code to be executed if condition is true;
} elseif (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
The example below will output "Have a good morning!" if the current time is less
than 10, and "Have a good day!" if the current time is less than 20. Otherwise it
will output "Have a good night!”
<?php
$t = date("H");
echo "<p>The hour (of the server) is " . $t;
echo ", and will give the following message:</p>";
4. switch Statement
Use the switch statement to select one of many blocks of code to be executed.
Syntax
switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
20
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}
How it works?
First we have a single expression n (most often a variable), that is
evaluated once.
The value of the expression is then compared with the values for each case
in the structure.
If there is a match, the block of code associated with that case is executed.
Use break to prevent the code from running into the next case
automatically.
The default statement is used if no match is found.
Example:
<?php
$favcolor = "red";
Output:
2. LOOPING STATEMENTS:
Looping statements are used to perform certain actions repeatedly when
the specified condition is true.
Loops:
Often when we write code, we want the same block of code to run over and
over again in a row. Instead of adding several almost equal code-lines in a
script, we can use loops to perform a task like this.
21
In PHP, we have the following looping statements:
while - loops through a block of code as long as the specified condition
is true
do...while - loops through a block of code once, and then repeats the
loop as long as the specified condition is true
for - loops through a block of code a specified number of times
foreach - loops through a block of code for each element in an array
1. while Loop
The while loop executes a block of code as long as the specified condition is true.
Syntax
while (condition is true) {
code to be executed;
}
The example below first sets a variable $x to 1 ($x = 1). Then, the while loop will
continue to run as long as $x is less than, or equal to 5 ($x <= 5). $x will
increase by 1 each time the loop runs ($x++):
Output:
<?php
$x = 1; The number is: 1
The number is: 2
while($x <= 5) { The number is: 3
echo "The number is: $x <br>"; The number is: 4
The number is: 5
$x++;
}
?>
2. do...while Loop
The do...while loop will always execute the block of code once, it will then check
the condition, and repeat the loop while the specified condition is true.
Syntax
do {
code to be executed;
} while (condition is true);
The example below first sets a variable $x to 1 ($x = 1). Then, the do while loop
will write some output, and then increment the variable $x with 1. Then the
condition is checked (is $x less than, or equal to 5?), and the loop will continue
to run as long as $x is less than, or equal to 5:
<?php
$x = 1;
22
Output:
do {
echo "The number is: $x <br>"; The number is: 1
$x++; The number is: 2
The number is: 3
} while ($x <= 5);
The number is: 4
?> The number is: 5
3. for Loop
PHP for loops execute a block of code a specified number of times.
The for loop is used when you know in advance how many times the script
should run.
Syntax
for (init counter; test counter; increment counter) {
code to be executed;
}
Parameters:
o init counter: Initialize the loop counter value
o test counter: Evaluated for each loop iteration. If it evaluates to
TRUE, the loop continues. If it evaluates to FALSE, the loop ends.
o increment counter: Increases the loop counter value
4. foreach Loop:
The foreach loop works only on arrays, and is used to loop through each
key/value pair in an array.
Syntax
foreach ($array as $value) {
code to be executed;
}
For every loop iteration, the value of the current array element is assigned to
$value and the array pointer is moved by one, until it reaches the last array
element.
The following example demonstrates a loop that will output the values of the
given array ($colors):
23
<?php Output:
$colors = array("red", "green", "blue", "yellow"); red
green
foreach ($colors as $value) { blue
echo "$value <br>"; yellow
}
?>
4.1.8: ARRAYS
An array is a data structure that stores one or more similar type of values
in a single value
There are three different kinds of arrays and each array value is accessed using
an ID which is called array index.
1) Numeric array - An array with a numeric index. Values are stored and
accessed in linear fashion.
2) Associative array - An array with strings as index. This stores element
values in association with key values rather than in a strict linear index
order.
3) Multidimensional array - An array containing one or more arrays and
values are accessed using multiple indices
CREATING ARRAYS:
In PHP, the array() function is used to create an array: array();
1. Numeric Array
These arrays can store numbers, strings and any object but their index will
be represented by numbers.
By default array index starts from zero.
Example
Following is the example showing how to create and access numeric arrays.
<html>
<body>
<?php
/* First method to create array. */
$numbers = array( 1, 2, 3, 4, 5);
$i=0;
foreach( $numbers as $value )
{
echo "numbers[$i] = $value <br />";
24
$i++;
}
/* Second method to create array. */ Output:
$numbers[0] = "one"; numbers[0] = 1
$numbers[1] = "two"; numbers[1] = 2
$numbers[2] = "three"; numbers[2] = 3
$numbers[3] = "four"; numbers[3] = 4
$numbers[4] = "five"; numbers[4] = 5
numbers[0] = one
numbers[1] = two
$i=0;
numbers[2] = three
foreach( $numbers as $value ) numbers[3] = four
{ numbers[4] = five
echo "numbers[$i] = $value <br />";
$i++;
}
?>
</body>
</html>
2. Associative Arrays
The associative arrays are very similar to numeric arrays in term of
functionality but they are different in terms of their index.
Associative array will have their index as string so that you can establish a
strong association between key and values.
To store the salaries of employees in an array, a numerically indexed array
would not be the best choice. Instead, we could use the employees names
as the keys in our associative array, and the value would be their
respective salary.
Example:
<html>
<body>
<?php
/* First method to associate create array. */
$salaries = array(
"AAA" => 2000,
"BBB" => 1000,
"CCC" => 500
);
25
/* Second method to create array. */
$salaries['AAA'] = "high";
$salaries['BBB'] = "medium";
$salaries['CCC'] = "low";
3. Multidimensional Arrays
A multi-dimensional array each element in the main array can also be an
array.
Each element in the sub-array can be an array, and so on.
Values in the multi-dimensional array are accessed using multiple index.
<html>
<body>
<?php
$marks = array(
"AAA" => array
( "physics" => 35,
"maths" => 30,
"chemistry" => 39 ),
26
/* Accessing multi-dimensional array values */
echo "Marks for AAA in physics : " ;
echo $marks['AAA']['physics'] . "<br />";
</body>
</html>
Output:
4.1.9: FUNCTIONS
Definition: A function is a piece of code which takes one or more input in the
form of parameter and does some processing and returns a value.
Creating functions:
Example:
<html>
<head>
<title>Writing PHP Function with Parameters</title>
</head>
<body>
27
<?php
function addFunction($num1, $num2) // function definition
{
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
</body>
</html>
Output:
Sum of the two numbers is : 30
function addSix(&$num)
{
$num += 6;
}
$orignum = 10;
addFive( $orignum );
28
echo "Original Value is $orignum<br />";
addSix( $orignum );
echo "Original Value is $orignum<br />";
?>
</body>
</html>
<?php
function addFunction($num1, $num2)
{
$sum = $num1 + $num2;
return $sum;
}
$return_value = addFunction(10, 20);
</body>
</html>
29
This will display following result –
Returned value from the function : 30
<!DOCTYPE html>
<html>
<body>
<?php
function setHeight($minheight = 50) {
echo "The height is : $minheight <br>";
}
setHeight(350);
setHeight(); // this function call will use the default value „50‟
setHeight(135);
setHeight(80);
?>
</body>
</html>
Output:
The height is : 350
The height is : 50
The height is : 135
The height is : 80
30
1. Array Functions:
These functions allow you to interact with and manipulate arrays in various
ways. Arrays are essential for storing, managing, and operating on sets of
variables.
Function Description
array() Create an array
array_chunk() Splits an array into chunks of arrays
array_combine() Creates an array by using one array for keys and
another for its values
array_count_values() Returns an array with the number of occurrences for
each value
array_key_exists() Checks if the specified key exists in the array
array_keys() Returns all the keys of an array
array_merge() Merges one or more arrays into one array
array_pop() Deletes the last element of an array
array_product() Calculates the product of the values in an array
array_push() Inserts one or more elements to the end of an array
array_rand() Returns one or more random keys from an array
array_reverse() Returns an array in the reverse order
array_search() Searches an array for a given value and returns the key
array_shift() Removes the first element from an array, and returns the
value of the removed element
array_slice() Returns selected parts of an array
array_splice() Removes and replaces specified elements of an array
array_sum() Returns the sum of the values in an array
sort() Sorts an array
<?php
$a = array('green', 'red', 'yellow');
$b = array('avocado', 'apple', 'banana');
$c = array_combine($a, $b);
echo "Comibination of Two Arrays : ";
print_r($c);
$c = array('avocado','watermelon','banana');
echo "<br>";
echo "Difference of Two Arrays : ";
print_r(array_diff($b,$c));
$d = array(10,4,2,7,1);
echo "<br>Sum of array = ";
print_r(array_sum($d));
31
echo "<br>product of array = ";
print_r(array_product($d));
Output:
Comibination of Two Arrays :
Array ( [green] => avocado [red] => apple [yellow] => banana )
Difference of Two Arrays : Array ( [1] => apple )
Sum of array = 24
product of array = 560
Sorting of array = Array ( [0] => 1 [1] => 2 [2] => 4 [3] => 7 [4] => 10 )
2. Class/Object Functions
These functions allow you to obtain information about classes and instance
objects.
You can obtain the name of the class to which an object belongs, as well as
its member properties and methods.
Function Description
class_exists() Checks if the class has been defined
get_class_methods() Gets the class methods' names
get_class_vars() Get the default properties of the class
get_class() Returns the name of the class of an object
get_object_vars() Gets the properties of the given object
get_parent_class() Retrieves the parent class name for object or class
is_a() Checks if the object is of this class or has this class
as one of its parents
method_exists() Checks if the class method exists
property_exists() Checks if the object or class has a property
Example:
<?php
class Box {
var $l = 10;
var $b = 20;
function volume()
{
$vol=$l*$b;
32
}
}
Output:
Variables in the class
l : 10
b : 20
Methods in the class
volume
3. Date Functions
These functions allow you to get the date and time from the server where your
PHP scripts are running.
Function Description
date_modify() Alters the timestamp
date_sunrise() Returns the time of sunrise for a given day / location
date_sunset() Returns the time of sunset for a given day / location
date_timezone_set() Sets the time zone for the DateTime object
date() Formats a local time/date
getdate() Returns an array that contains date and time information
for a Unix timestamp
gettimeofday() Returns an array that contains current time information
gmdate() Formats a GMT/UTC date/time
localtime() Returns an array that contains the time components of a
Unix timestamp
time() Returns the current time as a Unix timestamp
33
Example:
<?php
print date('r');
print "<br>";
print date('D, d M Y H:i:s T');
print "<br>";
?>
Output:
Thu, 03 Sep 2015 10:42:58 +0000
Thu, 03 Sep 2015 10:42:58 UTC
4. String Functions
String functions are used to manipulate strings.
Function Description
chr returns a specific character
count_chars return information about characters used in string
echo output one or more strings
fprintf write a formatted string to a stream
str_pad pad a string to a certain length with another string
str_repeat repeat a string
str_replace replace all occurrences of the search string with the
replacement string
str_ireplace case-insensitive version str_replace
strlen get string length
strcmp string comparison
strncmp string comparison of the first n characters
strpos find the position of the first occurrence of a substring in a
string
Example:
<html>
<body>
<?php
$str1="Welcome php";
echo "length of 'Welcome php' = ".strlen($str1)."<br>";
$str2="welcome php";
echo "compare(Welcome pjp , welcome php) =
".strcmp($str1,$str2)."<br>";
Output:
Form: A Document that containing black fields, that the user can fill the data or
user can select the data.
What is Validation?
Validation means check the input submitted by the user.
There are two types of validation are available in PHP. They are as follows −
Client-Side Validation − Validation is performed on the client machine web
browsers.
Server Side Validation − After submitted by data, The data has sent to a
server and perform validation checks in server machine.
The PHP superglobals $_GET and $_POST are used to collect form-data.
35
Example:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["name"];
$email = test_input($_POST["email"]);
$website = $_POST["website"];
$comment = $_POST["comment"];
$gender = $_POST["gender"];
}
36
function test_input($data) {
if(ereg("^[a-zA-Z0-9._-]+@[a-zA-Z0-9]+.[a-z.]{2,5}$",$data))
return "<script>alert('valid Email Id')</script>".$data;
else
return "false";
}
?>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
</body>
</html>
37
Output:
38
4.1.15: Connecting Database
39
40
41
42
43
4.2.1: Basics of XML
XML (eXtensible Markup Language) is a mark up language.
XML is a mark-up language that defines set of rules for encoding
documents in a format that is both human readable and machine
readable.
XML is designed to store and transport data.
Xml was released in late 90‟s. it was created to provide an easy to use and
store self-describing data.
XML became a W3C Recommendation on February 10, 1998.
XML is not a replacement for HTML.
XML is designed to be self-descriptive.
XML is designed to carry data, not to display data.
XML tags are not predefined. You must define your own tags.
XML is platform independent and language independent.
In this chapter, we will discuss the simple syntax rules to write an XML
document. Following is a complete XML document −
You can notice there are two kinds of information in the above example −
Markup, like <contact-info>
The text, or the character data, Tutorials Point and (040) 123-4567.
44
The following diagram depicts the syntax rules to write different types of markup
and text in an XML document.
XML Declaration
The XML document can optionally have an XML declaration. It is written as
follows −
<?xml version = "1.0" encoding = "UTF-8"?>
Where version is the XML version and encoding specifies the character encoding
used in the document.
Root Element − An XML document can have only one root element. For
example, following is not a correct XML document, because both
the x and y elements occur at the top level without a root element −
<x>...</x>
<y>...</y>
The Following example shows a correctly formed XML document −
<root>
<x>...</x>
<y>...</y>
</root>
XML Attributes
An attribute specifies a single property for the element, using a name/value
pair. An XML-element can have one or more attributes. For example −
<a href = "http://www.abc.com/">abc Tutorial!</a>
Here href is the attribute name and http://www.abc.com/ is attribute value.
46
Syntax Rules for XML Attributes
Attribute names in XML (unlike HTML) are case sensitive. That
is, HREF and href are considered two different XML attributes.
Same attribute cannot have two values in a syntax. The following example
shows incorrect syntax because the attribute b is specified twice
–
<a b = "x" c = "y" b = "z"> ......</a>
Attribute names are defined without quotation marks, whereas attribute
values must always appear in quotation marks. Following example
demonstrates incorrect xml syntax
–
<a b = x>. ....</a>
In the above syntax, the attribute value is not defined in quotation marks.
XML References
References usually allow you to add or include additional text or markup in an
XML document. References always begin with the symbol "&" which is a
reserved character and end with the symbol ";". XML has two types of references
–
Entity References − An entity reference contains a name between the
start and the end delimiters. For example & where amp is name.
The name refers to a predefined string of text and/or markup.
Character References − These contain references, such as A,
contains a hash mark (“#”) followed by a number. The number always
refers to the Unicode code of a character. In this case, 65 refers to
alphabet "A".
XML Text
The names of XML-elements and XML-attributes are case-sensitive, which
means the name of start and end elements need to be written in the same
case. To avoid character encoding problems, all XML files should be saved as
Unicode UTF-8 or UTF-16 files.
Whitespace characters like blanks, tabs and line-breaks between XML-
elements and between the XML-attributes will be ignored.
Some characters are reserved by the XML syntax itself. Hence, they cannot be
used directly. To use them, some replacement-entities are used, which are
listed below –
Not Allowed Character Replacement Entity Character Description
47
& & ampersand
48
6) XML Attribute values must always be quoted
XML elements can have attributes in name/value pairs just like in HTML.
In XML, the attribute values must always be quoted:
<note date="12/11/2007">
<to>Tove</to>
<from>Jani</from>
</note>
7) Entity References
Some characters have a special meaning in XML.
If you place a character like "<" inside an XML element, it will generate an error
because the parser interprets it as the start of a new element.
This will generate an XML error:
<message>salary < 1000</message>
To avoid this error, replace the "<" character with an entity reference:
<message>salary < 1000</message>
8) Comments in XML
The syntax for writing comments in XML is similar to that of HTML:
<!-- This is a comment -->
Two dashes in the middle of a comment are not allowed:
<!-- This is an invalid -- comment -->
Well Formed XML documents: XML documents that conform to the syntax
rules above are said to be "Well Formed" XML documents.
Valid XML Document:
If an XML document conforms to its DTD/Schema that defines the proper
structure of the document, then the XML document is valid XML document.
49
An XML document can reference a Document Type Definition (DTD) or a
schema that defines the proper structure of the XML document. When an XML
document references a DTD or a schema, XML parsers (called validating
parsers) can read the DTD/Schema and check that the XML document follows
the structure defined by the DTD/Schema. If the XML document conforms to the
DTD/schema, the XML document is valid.
XML HTML
Software and hardware independent Software and hardware dependent
To send and store data To display data
Focus on what data is present Focus on how data looks
It is a Framework for markup language
It is a markup language
definition
Case sensitive Case insensitive
Transport data between app and database Design client side web programs
Custom tags allowed Only predefined tags
Open and close tags are strict Not strict
White space insensitive White space insensitive
Carry information Display information
Dynamic Static
DTD stands for Document Type Definition. An XML DTD defines the
structure of an XML document.
XML DTD is used to define the basic building block of any XML
document. Using DTD, we can specify the various element types,
attributes, and their relationships with one another.
XML DTD is used to specify the set of rules for structuring data in any
XML file.
An XML document is considered “well formed” and “valid” if it is
successfully validated against DTD.
50
2. Attribute:- Used to specify the values of the element. It is to provide
additional information to an element.
3. CDATA:- Character Data. CDATA will be parsed by the parser.
4. PCDATA:- Parsed character data (ie. Text).
An example of DTD
DTD is declared inside<!DOCTYPE> definition when the DTD declaration is
internal. In this example we can see that there is an XML document that has a
<!DOCTYPE> definition. The bold part in the following example is the DTD
declaration.
<?xml version="1.0"?>
<!-- XML DTD declaration starts here -->
<!DOCTYPE beginnersbook [
<!ELEMENT beginnersbook (to,from,subject,message)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT subject (#PCDATA)>
<!ELEMENT message (#PCDATA)>
]>
<!-- XML DTD declaration ends here-->
<beginnersbook>
<to>My Readers</to>
<from>Chaitanya</from>
<subject>A Message to my readers</subject>
<message>Welcome to beginnersbook.com</message>
</beginnersbook>
Explanation:
!DOCTYPE beginnersbook defines that this is the beginning of the DTD declaration and the
51
52
Advantages of DTD
XML processor enforces structure, as defined in DTD
Application is accessed easily in document structure
DTD gives hint to XML processor
Reduces size of document
employee.xsd
1. <?xml version="1.0"?>
2. <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" >
3. <xs:element name="employee">
4. <xs:complexType>
5. <xs:sequence>
6. <xs:element name="firstname" type="xs:string"/>
7. <xs:element name="lastname" type="xs:string"/>
8. <xs:element name="email" type="xs:string"/>
9. </xs:sequence>
10. </xs:complexType>
11. </xs:element>
12. </xs:schema>
Let's see the xml file using XML schema or XSD file.
employee.xml
53
1. <?xml version="1.0"?>
2. <employee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="employee.xsd">
3.
4. <firstname>James</firstname>
5. <lastname>Gosling</lastname>
6. <email>[email protected]</email>
7. </employee>
1. Simple Type –
A simple element is an XML element that can contain only text. It cannot
contain any other elements or attributes.
It contains less attributes, child elements and cannot be left empty.
Simple type element is used only in the context of the text.
The syntax for defining a simple element is:
<xs:element name="xxx" type="yyy"/>
Some of predefined simple types are: xs:integer, xs:boolean, xs:string,
xs:date.
For example:
<xs:element name="phone_number" type="xs:int" />
2. Complex Type –
A complex type is a container for other element definitions.
This allows you to specify which child elements an element can contain
and to provide some structure within your XML documents.
For example:
54
<xs:element name="Address">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string" />
<xs:element name="company" type="xs:string" />
<xs:element name="phone" type="xs:int" />
</xs:sequence>
</xs:complexType>
</xs:element>
3. Global Types –
With global type, you can define a single type in your document, which
can be used by all other references.
For example, suppose you want to generalize the person and company
for different addresses of the company. In such case, you can define a
general type as below:
<xs:element name="AddressType">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string" />
<xs:element name="company" type="xs:string" />
</xs:sequence>
</xs:complexType>
</xs:element>
55
Instead of having to define the name and the company twice (once for
Address1 and once for Address2), we now have a single definition.
This makes maintenance simpler, i.e., if you decide to add "Postcode"
elements to the address, you need to add them at just one place.
xs:string
xs:decimal
xs:integer
xs:boolean
xs:date
xs:time
i) <xs:string> data type
The <xs:string> data type can take characters, line feeds, carriage returns,
and tab characters.
The XML processor does not replace line feeds, carriage returns, and tab
characters in the content with space and keep them intact.
For example, multiple spaces or tabs are preserved during display.
Example
56
<lastname>Refsnes</lastname>
<age>36</age>
<dateborn>1970-03-27</dateborn>
57
DIFFERENCE BETWEEN XML DTD & XML SCHEMA DEFINITION (XSD)
58
4.2.6: XML Parsers and Validation
XML parser validates the document and check that the document is well
formatted.
59
The DOM approach is useful for The SAX approach is useful for
smaller applications because it parsing the large XML document
is simpler to use but it is because it is event based, XML
4. certainly not used for larger gets parsed node by node and
XML documents because it will does not require large amount of
then require larger amount of memory
memory
5. We can insert or delete a node We can insert or delete a node
Traversing is done in any Top to bottom traversing is done
6.
direction in DOM approach in SAX approach
Example: Checking the Well Formedness of XML document using DOM API.
dom.java
import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.*;
User.xml
<?xml version="1.0"?>
<userdata>
<user1>
<userno>001</userno>
<username>Bala</username>
<phonenumner>123456789</phonenumber>
<address>Chennai</Chennai>
</user1>
<user2>
<userno>002</userno>
<username>Suresh</username>
<phonenumner>987654321</phonenumber>
<address>madurai</Chennai>
</user2>
<user3>
<userno>003</userno>
<username>arul</username>
<phonenumner>1122334455</phonenumber>
<address>Vellore</Chennai>
</user3>
</userdata>
61
Output:
C:> javac dom.java
C:> java dom
Enter file name dom.xml
dom.xml is well formed
62
Program Explanation:
63
Output:
Advantages
1) It supports both read and write operations and the API is very simple to use.
2) It is preferred when random access to widely separated parts of a document is
required.
Disadvantages
1) It is memory inefficient. (Consumes more memory because the whole XML
document needs to loaded into memory).
2) It is comparatively slower than other parsers.
Example: Checking the Well Formedness of XML document using SAX API.
import java.io.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
public class Parsing_SAXDemo
{
public static void main(String bala[])
{
try
{
System.out.println(“Enter XML document name”);
BufferedReader input = new BufferedReader( new InputStreamReader(System.in));
String filename = input.readLine();
File fp = new File(filename);
64
if(fp.exists())
{
try
{
XMLReader reader = XMLReaderFactory.CreateXMLReader();
reader.parse(filename);
System.out.println(“filename + “is well formed”);
}
catch(Exception e)
{
System.out.println(“filename + “is not well formed”);
System.exit(1);
}
}
else
{
System.out.println(“file not found”);
}
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
}
Output:
65
Advantages
1) It is simple and memory efficient.
2) It is very fast and works for huge documents.
Disadvantages
1) It is event-based so its API is less intuitive.
2) Clients never know the full information because the data is broken into pieces.
XSL document
XSL Elements:
Elements Description
<xsl:template> Contains rules to apply when a
specified node is matched. The
“match” attribute is associated with
this element. The match= “/” defines
the whole document.
<xsl:value-of select = “expression”> Selects the value of an XML element
and adds it to the output tree. The
select attribute contains an XPath
expression.
<xsl:for-each select = “expression”> Applies a template to every node
selected by the XPath expression.
<xsl:sort select = “expression”> Sorts the nodes selected by <<xsl:for-
67
each select = “expression”> element.
<xsl:output> Used to define the format of the output
document.
<xsl:copy> Adds the current node to the output
tree.
68
<address>chennai</address>
</student>
<student>
<name>EEE</name>
<reg_no>2002</reg_no>
<year>1</year>
<semester>II</semester>
<grade>C</grade>
<address>chennai</address>
</student>
</student-details>
Stud.xsl
69
</xsl:for-each>
</table>
<hr/>
<h1>First Year Students</h1>
<table border="1">
<tr bgcolor="white">
<th>Name</th>
<th>Register No</th>
<th>Year</th>
<th>Semester</th>
<th>Grade</th>
<th>Address</th>
</tr>
70
<td><xsl:value-of select="semester"/></td>
<td><xsl:value-of select="grade"/></td>
<td><xsl:value-of select="address"/></td>
</tr>
</xsl:for-each>
</table>
</center>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
OUTPUT:
71
PART A
<?php
echo "Hello World!";
?>
72
</body>
</html>
<?php
setcookie("name", "John Watkin", time()+3600, "/","", 0);
setcookie("age", "36", time()+3600, "/", "", 0);
?>
18. What are the two sets of regular expressions offered by PHP?
PHP offers functions specific to two sets of regular expression functions:
POSIX extended Regular Expressions
PERL compatible Regular Expressions
The ereg() function searches a string specified by string for a string specified by pattern,
ereg()
returning true if the pattern is found, and false otherwise.
The ereg_replace() function searches for string specified by pattern and replaces pattern
ereg_replace()
with replacement if found.
The eregi() function searches throughout a string specified by pattern for a string
eregi()
specified by string. The search is not case sensitive.
The eregi_replace() function operates exactly like ereg_replace(), except that the search
eregi_replace()
for pattern in string is not case sensitive.
The split() function will divide a string into various elements, the boundaries of each
split()
element based on the occurrence of pattern in string.
The spliti() function operates exactly in the same manner as its sibling split(), except that
spliti()
it is not case sensitive.
75
sql_regcase() The sql_regcase() function can be thought of as a utility function, converting each
character in the input parameter string into a bracketed expression containing two
characters.
The preg_match() function searches string for pattern, returning true if pattern exists,
preg_match()
and false otherwise.
The preg_replace() function operates just like ereg_replace(), except that regular
preg_replace()
expressions can be used in the pattern and replacement input parameters.
The preg_split() function operates exactly like split(), except that regular expressions
preg_split()
are accepted as input parameters for pattern.
The preg_grep() function searches all elements of input_array, returning all elements
preg_grep()
matching the regexp pattern.
25. What do you mean by XML declaration? Give an example. (MAY/JUNE 2013)
The XML declaration is a processing instruction that identifies the document as being
XML. All XML documents should begin with an XML declaration.
For example,
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
26. What is meant by a XML namespace?(April / May 2011, 2014, Nov / Dec 2012,
2013,NOV/DEC 2016)
An XML namespace is a collection of element and attribute names. XML namespace provide a
means for document authors to unambiguously refer to elements with the same name (i.e., prevent
collisions).
Example:
<subject>Geometry</subject> // data for student from school
and
<subject>Cardiology</subject> // data for student from medicine
Both the markup uses the element “subject” to markup data. Namespace can differentiate these two
“subject” elements:
<highschool:subject>Geometry</highschool:subject>
and <medicalschool:subject>Cardiology</medicalschool:subject>
Example:
77
<root>
<highschool:subject xmlns:highschool="http://www.abcschool.edu/subjects">
Geometry
</highschool:subject>
<medicalschool:subject xmlns:medicalshool="http://www.rmc.org/subjects">
Cardiology
</medicalschool:subject>
</root>
Example DTD :
<!DOCTYPE note
[
<!ELEMENT note (to,from,heading,body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>
]>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget to complete the work !</body>
< </note>
78
<!DOCTYPE root-element [element-declarations]>
where root-element is the name of root element and element-declarations is where you declare the
elements.
Example
Following is a simple example of internal DTD:
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<!DOCTYPE address [
<!ELEMENT address (name,company,phone)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT company (#PCDATA)>
<!ELEMENT phone (#PCDATA)>
]>
<address>
<name>Tanmay Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 123-4567</phone>
</address>
79
33. Give the syntax to declare XML schema.
Syntax:
The common syntax to declare a schema in our XML document as follows:
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
The structure of the node tree begins with the root element and spreads out to the child elements till the
lowest level.
The nodes in the node tree have a hierarchical relationship to each other.The terms parent, child, and
sibling are used to describe the relationships. Parent nodes have children. Children on the same level are
called siblings (brothers or sisters).
80
In a node tree, the top node is called the root
Every node, except the root, has exactly one parent node
A node can have any number of children
A leaf is a node with no children
Siblings are nodes with the same parent
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE addresses SYSTEM "addresses.dtd">
<addresses>
<person idnum="0123">
<lastName>Doe</lastName>
<firstName>John</firstName>
<phone location="mobile">(201) 345-6789</phone>
<email>[email protected]</email>
<address>
<street>100 Main Street</street>
<city>Somewhere</city>
<state>New Jersey</state>
<zip>07670</zip>
</address>
</person>
</addresses>
The following tree of element nodes represents this document:
81
39. Explain the use of XML Parser. (APRIL/MAY 2022)
It checks for proper format of the XML document (Well Formed Document) and may also validate
the XML documents (Valid XML Document).
XML parser validates the document and check that the document is well formatted.
43. What are the two types of XML parsers? And differentiate them.(U/AN)
Two types of XML Parsers:
1. Non-Validating XML Parsers
2. Validating XML Parsers
Non-Validating XML Parsers Validating XML Parsers
A non-validating parser checks if a document A Validating parser checks the syntax, builds
follows the XML syntax rules. It builds a tree the tree structure, and compares the structure
structure from the tags used in XML document of the XML document with the structure
and return an error only when there is a specified in the DTD associated with the
problem with the syntax of the document. document.
Non validating parsers process a document Validating parsers are slower because, in
faster because they do not have to check every addition to checking whether an XML document
element against a DTD. In other words, these is well formed; validating parsers also check
parsers check whether an XML document whether the XML document adheres to the
adheres to the rules of well-formed document. rules in the DTD used by the XML document.
The Expat parser is an example of non- Microsoft MSXML parser is an example of a
validating parser. validating parser.
82
Define XSL.
The Extensible Style sheet Language (XSL) is an XML vocabulary that decides how an XML
document data should look on the web browser. XSL is group of three technoliges:
1. XSL Transformations (XSLT): is technology for transforming the structure of the XML document
data into another structure.
2. XML Path Language (XPath): is a string-based language of expressions which defines the syntax
and semantics for efficiently locating elements and attributes in XML documents.
3. XSL Formatting Objects (XSL-FO): It is a separate XML vocabulary for defining document style
properties of an XML document .(print-oriented)
83
49. Why is XSLT an important tool in development of web applications?
(MAY/JUNE 2016)
XSLT is the most important part of XSL.
XSLT is used to transform an XML document into another XML document, or another type of
document that is recognized by a browser, like HTML and XHTML. Normally XSLT does this
by transforming each XML element into an (X)HTML element.
With XSLT you can add/remove elements and attributes to or from the output file. You can also
rearrange and sort elements, perform tests and make decisions about which elements to hide and
display, and a lot more.
A common way to describe the transformation process is to say that XSLT transforms an XML
source-tree into an XML result-tree.
50. When should the super global arrays in PHP be used? Which super global array in PHP would
contain a HTML form's POST data? (MAY/JUNE 2016)
PHP super global variable is used to access global variables from anywhere in the PHP script.
There are two different types of form validation – Client side validation and Server side validations.
PART – B
1. Discuss in detail about how to create and use variables in PHP with example program.
2. What are the different data types available in PHP? Explain about converting between
different data types with example program.
3. Write a PHP program using arithmetic operator.
4. Explain the features of built-in functions in PHP with examples. (APRIL/MAY 2022)
5. Write a PHP program to do string manipulation. (NOV / DEC 2015)
6. Explain how user-defined functions are created in PHP.
7. Explain how input from an XHTML form is received in a PHP program.
8. How will you connect a PHP program with database? Explain with example application.
9. Explain how cookies are handled in PHP.
10. Explain in detail about using Regular Expressions in PHP.
11. Explain XML DTD. (APRIL/MAY 2022)
12. What are different types of DTD? Explain the same with example.
13. Explain the role of XML name spaces with examples. (MAY/JUNE 2012)
14. What is XML Schema? Explain how to create and use XML Schema document.
84
(NOV/DEC 2015)
15. Explain how a XML document can be displayed on a browser. (APRIL/MAY 2011)
16. Explain Document Tree with an example. (MAY/JUNE 2011, MAY/JUNE 2012)
17. Explain in detail about XSL. (NOV/ EC 2013)
18. Give an XSLT document and a source XML document explain the XSLT transformation
process that produces a single result XML document. (NOV/DEC 2012)
19. Explain in detail about XML parsers and validation. (NOV/DEC 2015, MAY/JUNE 2016)
20. Create a webserver based chat application using PHP. The application should provide the function
functions.
Login
Send message (to one or more contacts)
Receive messages(from one or more contacts)
Add/delete /modify contact list of the user
21. Discuss the application’s user interface and use comments in PHP to explain the code clearly.
(MAY/JUNE 2016)
22. List at least five significant differences between DID and XML schema for defining XML
document structures with appropriate examples. (MAY/JUNE 2016)
23. Explain the string comparison capability of PHP using regular expressions with an
example. (NOV/DEC2016)
24. Explain the steps in connecting a PHP code to a database. (NOV/DEC2016)
25. Explain in detail the XML schema, built in and user defined data type in detail.
(NOV/DEC2016)
26. Design simple calculator using PHP. (NOV/DEC2018)
27. Explain about the controls statements in PHP with example. (NOV/DEC 2018)
28. Design a PHP application for College Management System with appropriate built-in functions and
database. (NOV/DEC 2018)
29. What is spring framework ? What is use of it ? What are the advantages of Spring Framework?
(APRIL/MAY 2021)
30. Using XSLT, how would you extract a specific attribute from an element in an Xml document?
When constructing an XML DTD, how do you create an external entity reference in an attribute
value ? (APRIL/MAY 2021)
31. Write the HTML code for creating a feedback form as shown below. Include comments in code to
highlight the markup elements and their purpose. The HTML form should use POST for
submitting the form to a program ProcessContactForm.PHP. (MAY/JUNE 2016)
Internet Programming
35. Illustrate the steps and procedure to connect the PHP to any database. write a program of your own
demonstrate (NOV-DEC 2022)
36. Write a program using PHP to check whether the input to a function calculating factorial is valid(>0) or
not(NOV-DEC 2022)
85