0% found this document useful (0 votes)
28 views86 pages

Unit - 4

program

Uploaded by

jananisb2207
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views86 pages

Unit - 4

program

Uploaded by

jananisb2207
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 86

UNIT IV PHP and XML

An introduction to PHP: PHP- Using PHP- Variables- Program control- Built-


in functions- Form Validation- XML: Basic XML- Document Type Definition-
XML Schema, XML Parsers and Validation, XSL.
4.1.1: INTRODUCTION TO PHP

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.

What is a PHP File?


o PHP files can contain text, HTML, CSS, JavaScript, and PHP code.
o PHP codes are executed on the server, and the result is returned to the
browser as plain HTML.
o PHP files have extension ".php"

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

4.1.2: PHP – BASIC SYNTAX

BASIC PHP SYNTAX:


 A PHP script can be embedded directly and anywhere in the HTML
document.
 A PHP script starts with <?php and ends with ?>:
 Syntax: <?php
// PHP code goes here
?>
 The default file extension for PHP files is ".php".
 A PHP file normally contains HTML tags, and some PHP scripting code.

2
 "echo" – statement used to output the text on a web page:

<!DOCTYPE html>
<html>
<body>

<h1>My first PHP page</h1>

<?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 Case Sensitivity:


 In PHP, all keywords (e.g. if, else, while, echo, etc.), classes, functions, and
user-defined functions are NOT case-sensitive.
 However; all variable names are case-sensitive.
 Example:
<!DOCTYPE html>
<html>
<body>

<?php
// all the echo statements are treated as same
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";

// all the variables are treated as three different variables


$color = "red";
echo "My car is " . $color . "<br>";
echo "My house is " . $COLOR . "<br>";
echo "My boat is " . $coLOR . "<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

Definition: Variables are "containers" for storing information.

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;

Rules for PHP variables:


 A variable starts with the $ sign, followed by the name of the variable name.
 A variable can have a short name (like x and y) or a more descriptive name
(age, carname, total_volume).
 A variable name must start with a letter or the underscore character.
 A variable name cannot start with a number.
 A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ ) but cannot use characters like + , - , % , ( , ) .
&, etc.
 Variable names are case-sensitive ($age and $AGE are two different
variables).

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:

My variable contains the value of 10

PHP VARIABLES SCOPE:

 In PHP, variables can be declared anywhere in the script.


 The scope of a variable is the part of the script where the variable can be
referenced / used.
 PHP has three different variable scopes:
 Local
 Global
 Static

 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.

 PHP The static Keyword


 Normally, when a function is completed/executed, all of its variables are
deleted. However, sometimes we want a local variable NOT to be deleted.
We need it for a further job.
 To do this, use the static keyword when you first declare the variable:

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

 PHP The global Keyword


The global keyword is used to access a global variable from within a
function.
To do this, use the global keyword before the variables (inside the
function):

 PHP also stores all global variables in an array called $GLOBALS[index].


 The index holds the name of the variable.
 Example
<?php
$x = 5;
$y = 10;

function myTest() {
$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
}

myTest();
echo $y; // outputs 15
?>

4.1.4: PHP – OUPUT STATEMENTS

 PHP echo and print Statements:


 echo and print are more or less the same. They are both used to output
data to the screen.
 The differences are small:
o echo has no return value while print has a return value of 1 so it can
be used in expressions.

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>";

echo("X + Y = ".($x + $y));


?>

Output:

Learn PHP
Study PHP at deitel.com
X+Y=9

4.1.5: PHP – DATA TYPES

Variables can store data of different types, and different data types can do
different things.

PHP supports the following data types:

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 NULL Value:


 Null is a special data type which can have only one value: NULL.
 A variable of data type NULL is a variable that has no value assigned to it.
 If a variable is created without a value, it is automatically assigned a value
of NULL.
 Variables can also be emptied by setting the value to NULL:
 $x = null;

 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.

Example: Program using all the data types:

<!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

class Car { // class declartion


function carModel() { // function inside class
$this->model = "VW";
echo "Car Model from Object = ".$this->model."<br>";
}
}
?>
<font color="blue" style="bold">

<?php

10
// create an object
$herbie = new Car(); // creating object for car class

// show object properties


echo $herbie->carModel(); //Invoking function through object

var_dump($x); echo "<br>";


var_dump($y); echo "<br>";
var_dump($str1); echo "<br>";
var_dump($str2); echo "<br>";
var_dump($bool1); echo "<br>";
var_dump($bool2); echo "<br>";
var_dump($cars); echo "<br>";
?>
</font>
</body>
</html>

Output:

Car Model from Object = VW


int(5985)
float(59.85)
string(6) "Hello "
string(5) "World"
bool(true)
bool(false)
array(3) { [0]=> string(5) "Volvo" [1]=> string(3) "BMW" [2]=> string(6) "Toyota" }
CONVERSION BETWEEN DATA TYPES (TYPE COVERSION):
 Type Conversion is the process of converting one data type into another.
 Converting between different data types may be necessary when performing
arithmetic operations with variables.
 Type conversions can be performed using the function settype.
 Syntax:
settype($variable_name, “data_type”);
 We can print the value of variables and their types using the function
gettype.
 Syntax:
gettype($variable_name);
 Type Casting:
Another option for conversion between types is casting. Unlike
settype, casting does not change a variable‟s content – it creates a
11
temporary copy of a variable‟s value in memory. Casting is useful when a
different type is required in a specific operation but you would like to retain
the variable‟s original value and type.

 Example:
<!DOCTYPE html>
<html>
<body>
<?php

$var1="114";
$var2=114.12;
$var3=114;

print("$var1 is of ".gettype($var1)." type <br/>");


print("$var2 is of ".gettype($var2)." type <br/>");
print("$var3 is of ".gettype($var3)." type <br/>");

echo("<b><u> Converting into other datatype </u></b><br/>");

settype($var1,"double");
settype($var2,"integer");
settype($var3,"string");

print("$var1 is of ".gettype($var1)." type <br/>");


print("$var2 is of ".gettype($var2)." type <br/>");
print("$var3 is of ".gettype($var3)." type <br/>");

echo("<b><u> Type Casting </u></b><br/>");


$data="98.6 degrees";
print("<b>Before Casting : data is of ".gettype($data)." type </b><br/>");
print("After Casting into double : value of data = ".(double)$data. "<br/>");
print("After Casting into integer : value of data = ".(int)$data. "<br/>");
print("<b>After Casting : data is of ".gettype($data)." type </b><br/>");

?>
</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>

DIFFERENCES BETWEEN CONSTANTS AND VARIABLES:


 There is no need to write a dollar sign ($) before a constant, where as in
Variable one has to write a dollar sign.
 Constants cannot be defined by simple assignment, they may only be
defined using the define() function.
 Constants may be defined and accessed anywhere without regard to
variable scoping rules.
 Once the Constants have been set, may not be redefined or undefined.

4.1.6: PHP – OPERATORS

Operators are used to perform operations on variables and values.

PHP divides the operators in the following groups:


1) Arithmetic operators
2) Assignment operators
3) Comparison operators
4) Increment/Decrement operators
5) Logical operators
6) String operators
7) Array operators

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)

 PHP Assignment Operators


 The PHP assignment operators are used with numeric values to write a
value to a variable.
 The basic assignment operator in PHP is "=". It means that the left operand
gets set to the value of the assignment expression on the right.
Assignment Same as... Description
x=y x=y The left operand gets set to the value of the
expression on the right
x += y x=x+y Addition
x -= y x=x-y Subtraction
x *= y x=x*y Multiplication
x /= y x=x/y Division
x %= y x = x % y Modulus

 PHP Comparison Operators


 The PHP comparison operators are used to compare two values (number or
string):

Operator Name Example Result


== Equal $x == $y Returns true if $x is equal to $y
=== Identical $x === $y Returns true if $x is equal to $y, and
they are of the same type
!= Not equal $x != $y Returns true if $x is not equal to $y
<> Not equal $x <> $y Returns true if $x is not equal to $y
!= = Not identical $x !== $y Returns true if $x is not equal to $y,
or they are not of the same type
> Greater than $x > $y Returns true if $x is greater than $y
< Less than $x < $y Returns true if $x is less than $y
>= Greater than or $x >= $y Returns true if $x is greater than or
equal to equal to $y
<= Less than or $x <= $y Returns true if $x is less than or
equal to equal to $y

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

 PHP Logical Operators


 The PHP logical operators are used to combine conditional statements.
Operator Name Example Result
and And $x and $y True if both $x and $y are true
or Or $x or $y True if either $x or $y is true
xor Xor $x xor $y True if either $x or $y is true, but not both
&& And $x && $y True if both $x and $y are true
|| Or $x || $y True if either $x or $y is true
! Not !$x True if $x is not true

 PHP String Operators


 PHP has two operators that are specially designed for strings.
Operator Name Example Result
. Concatenation $txt1 . $txt2 Concatenation of $txt1
and $txt2
.= Concatenation $txt1 .= $txt2 Appends $txt2 to $txt1
assignment

 PHP Array Operators


 The PHP array operators are used to compare arrays.

Operator Name Example Result


+ Union $x + $y Union of $x and $y
== Equality $x == $y Returns true if $x and $y have the same
key/value pairs
=== Identity $x === $y Returns true if $x and $y have the same
key/value pairs in the same order and
of the same types
!= Inequality $x != $y Returns true if $x is not equal to $y
<> Inequality $x <> $y Returns true if $x is not equal to $y
!== Non- $x !== $y Returns true if $x is not identical to $y
identity

Example:
<html>
<head><title>Logical Operators</title><head>

16
<body>
<?php
$x=10;
$y=5;

echo "<b><u> Arithmetic Operators </u></b><br/>";


echo "Add = $x+$y = ".($x+$y)." <br>";
echo "Sub = $x-$y = ".($x-$y)." <br>";
echo "Mul = $x*$y = ".($x*$y)." <br>";
echo "Div = $x/$y = ".($x/$y)." <br>";

echo "<b><u> Assignment Operators </u></b><br/>";


echo "Add = ".($x+=$y)." <br>";
echo "Sub = ".($x-=$y)." <br>";
echo "Mul = ".($x*=$y)." <br>";
echo "Div = ".($x/=$y)." <br>";

echo "<b><u> Increment / Decrement Operators </u></b><br/>";


echo "Pre-Increment = ".++$x." <br>";
echo "Post - Increment = ".$x++." <br>";
echo "After Increment = ".$x."<br/>";

echo "<b><u> Relational Operators </u></b><br/>";


echo " => $x<$y ".var_dump($x<$y)." <br>";
echo " => $x>$y ".var_dump($x>$y)." <br>";
echo " => $x<=$y ".var_dump($x<=$y)." <br>";
echo " => $x>=$y ".var_dump($x>=$y)." <br>";
echo " => $x!=$y ".var_dump($x!=$y)." <br>";

echo "<b><u> Logical Operators </u></b><br/>";


echo " => $x&&$y ".var_dump($x&&$y)." <br>";
echo " => $x||$y ".var_dump($x||$y)." <br>";
echo " => $x xor $y ".var_dump($x xor $y)." <br>";

?>
</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

4.1.7: PROGRAM CONTROL


There are two control flow statements are used in PHP:
1. Conditional or Decision making Statements
2. Looping Statements

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:

if ($t < "20") { Have a good day!


echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>

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>";

if ($t < "10") {


echo "Have a good morning!";
} elseif ($t < "20") { Output:
echo "Have a good day!";
The hour (of the server) is 03, and will
} else { give the following message:
echo "Have a good night!";
} Have a good morning!
?>

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:

switch ($favcolor) { Your favorite color is red!


case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
?>

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

The example below displays the numbers from 0 to 10:


<?php Output:
for ($x = 0; $x <= 5; $x++) {
The number is: 1
echo "The number is: $x <br>";
The number is: 2
}
The number is: 3
?> The number is: 4
The number is: 5

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();

Syntax: $array_variable = array(“value1”, “value2”, ….., “valueN”);

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
);

echo "Salary of AAA is ". $salaries['AAA'] . "<br />";


echo "Salary of BBB is ". $salaries['BBB']. "<br />";
echo "Salary of CCC is ". $salaries['CCC']. "<br />";

25
/* Second method to create array. */
$salaries['AAA'] = "high";
$salaries['BBB'] = "medium";
$salaries['CCC'] = "low";

foreach($salaries as $x => $x_value) {


echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>"; Output:
}
?> Salary of AAA is 2000
Salary of BBB is 1000
</body>
Salary of CCC is 500
</html> Key=AAA, Value=high
Key=BBB, Value=medium
Key=CCC, Value=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 ),

"BBB" => array


( "physics" => 30,
"maths" => 32,
"chemistry" => 29 ),

"CCC" => array


( "physics" => 31,
"maths" => 22,
"chemistry" => 39 )
);

26
/* Accessing multi-dimensional array values */
echo "Marks for AAA in physics : " ;
echo $marks['AAA']['physics'] . "<br />";

echo "Marks for BBB in maths : ";


echo $marks['BBB']['maths'] . "<br />";

echo "Marks for CCC in chemistry : " ;


echo $marks['CCC']['chemistry'] . "<br />";
?>

</body>
</html>

Output:

Marks for AAA in physics : 35


Marks for BBB in maths : 32
Marks for CCC in chemistry : 39

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:

Syntax: function functionName(parameter_list)


{
Function body
}

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";
}

addFunction(10, 20); // function call


?>

</body>
</html>

Output:
Sum of the two numbers is : 30

Passing Arguments by Reference:


 It is possible to pass arguments to functions by reference. This means that
a reference to the variable is manipulated by the function rather than a
copy of the variable's value.
 Any changes made to an argument in these cases will change the value of
the original variable.
 You can pass an argument by reference by adding an ampersand to the
variable name in either the function call or the function definition.
 Example:
<html>
<head>
<title>Passing Argument by Reference</title>
</head>
<body>
<?php
function addFive($num)
{ $num += 5; }

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>

This will display following result −


Original Value is 10
Original Value is 16

PHP Functions returning value:


 A function can return a value using the return statement in conjunction
with a value or object.
 return stops the execution of the function and sends the value back to the
calling code.
 You can return more than one value from a function using return
array(1,2,3,4).
 Following example takes two integer parameters and add them together
and then returns their sum to the calling program. Note that return
keyword is used to return a value from a function.
<html>
<head>
<title>Writing PHP Function which returns value</title>
</head>
<body>

<?php
function addFunction($num1, $num2)
{
$sum = $num1 + $num2;
return $sum;
}
$return_value = addFunction(10, 20);

echo "Returned value from the function : $return_value";


?>

</body>
</html>

29
This will display following result –
Returned value from the function : 30

Setting Default Values for Function Parameters


We can set a parameter to have a default value if the function's caller
doesn't pass it.

<!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

4.1.10: PHP BUILT-IN FUNCTIONS


 Array Functions
 Class/Object Functions
 Character Functions
 Date & Time Functions
 Error Handling Functions
 MySQL Functions
 ODBC Functions
 String Functions
 XML Parsing Functions

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));

echo "<br>Sorting of array = ";


sort($d);
print_r($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
}
}

$obj = new Box();


$class_vars = get_class_vars(get_class($obj));
$class_methods = get_class_methods(new Box());

echo "Variables in the class <br>";


foreach ($class_vars as $name => $value) {
echo "$name : $value <br>";
}

echo "Methods in the class <br>";


foreach ($class_methods as $method_name) {
echo "$method_name <br>";
}
?>

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>";

echo "str1 in uppercase = ".strtoupper($str1)."<br>";


?>
34
Downloaded from EnggTree.com
</body>
</html>

Output:

4.1.12: PHP FORM HANDLING

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.

Some of Validation rules for field


Field Validation Rules
Name Should require letters and white-spaces
Email Should require @ and .
Website Should require a valid URL
Radio Must be selectable at least once
Check Box Must be checkable at least once
Drop Down menu Must be selectable at least once

Collecting form data in PHP:

The PHP superglobals $_GET and $_POST are used to collect form-data.

superglobal arrays: superglobal arrays are used to obtain client information


from the request. They are associative arrays that hold variables acquired from user
input.

35

Other useful superglobal arrays:


variable name Description
$_SERVER Data about the currently running server
$_ENV Data about the client‟s environment
$_GET Data sent to the server by a get request
$_POST Data sent to the server by a post request
$_COOKIE Data contained in the cookies on the client computer
$_GLOBALS Array containing all global variables

When to use GET?


 Information sent from a form with the GET method is visible to everyone
(all variable names and values are displayed in the URL).
 GET also has limits on the amount of information to send. The limitation is
about 2000 characters. However, because the variables are displayed in the
URL, it is possible to bookmark the page. This can be useful in some cases.
 GET may be used for sending non-sensitive data.

When to use POST?


 Information sent from a form with the POST method is invisible to others
(all names/values are embedded within the body of the HTTP request) and
has no limits on the amount of information to send.

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";
}
?>

<h2>PHP Form Validation Example</h2>


<form method="post" action="forms.php">
Name: <input type="text" name="name">
<br><br>
E-mail: <input type="text" name="email">
<br><br>
Website: <input type="text" name="website">
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<br><br>
<input type="submit" name="submit" value="Submit">
</form>

<?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.

Features of XML / Advantages / Uses


 Simplify the creation of HTML documents for large sites
 To exchange information between organizations
 Offload and reload databases
 Store and arrange data
 Any type of data can be expressed in XML
 Suits well for commerce applications, scientific purposes, mathematics,
chemical formulae
 It can be used in handheld devices, smartphones, etc
 Hardware, software and language independent

4.2.2: XML Syntax Rules

In this chapter, we will discuss the simple syntax rules to write an XML
document. Following is a complete XML document −

<?xml version = "1.0"?>


<contact-info>
<name>Tanmay Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 123-4567</phone>
</contact-info>

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.

Let us see each component of the above diagram in detail.

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.

Syntax Rules for XML Declaration


 The XML declaration is case sensitive and must begin with "<?xml>" where
"xml" is written in lower-case.
 If document contains XML declaration, then it strictly needs to be the first
statement of the XML document. 
 The XML declaration strictly needs be the first statement in the XML
document.
 An HTTP protocol can override the value of encoding that you put in the
XML declaration. 

Tags and Elements


An XML file is structured by several XML-elements, also called XML-nodes or XML-
tags. The names of XML-elements are enclosed in triangular brackets < > as
shown below −
<element>

Syntax Rules for Tags and Elements


Element Syntax − Each XML-element needs to be closed either with start or
with end elements as shown below −
45
Downloaded from EnggTree.com
<element> ..... </element>
or in simple-cases, just this way −
<element/>

Nesting of Elements − An XML-element can contain multiple XML-elements as


its children, but the children elements must not overlap. i.e., an end tag of an
element must have the same name as that of the most recent unmatched start
tag.
The Following example shows incorrect nested tags −
<?xml version = "1.0"?>
<contact-info>
<company>ABC
</contact-info>
</company>
The Following example shows correct nested tags −
<?xml version = "1.0"?>
<contact-info>
<company>ABC</company>
<contact-info>

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>

Case Sensitivity − The names of XML-elements are case-sensitive. That means


the name of the start and the end elements need to be exactly in the same case.
For example, <contact-info> is different from <Contact-Info>

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 &amp; where amp is name.
The name refers to a predefined string of text and/or markup. 
 Character References − These contain references, such as &#65;,
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

< &lt; less than

> &gt; greater than

47
& &amp; ampersand

' &apos; apostrophe

" &quot; quotation mark

XML Syntax Rules (Quick Recap..)

1) XML documents must have a root element.


XML documents must contain one root element that is the parent of all other
elements:
<root>
<child>
<subchild> ....... </subchild>
</child>
</root>

2) The XML Prolog


This line is called the XML prolog:
<?xml version="1.0" encoding="UTF-8"?>
The XML prolog is optional. If it exists, it must come first in the document.

3) All XML Elements Must Have a Closing Tag


In XML, it is illegal to omit the closing tag. All elements must have a closing tag:
<p>This is a paragraph.</p>
<br />

4) XML Tags are Case Sensitive


XML tags are case sensitive. The tag <Letter> is different from the tag <letter>.
Opening and closing tags must be written with the same case:
<message>This is correct</message>
"Opening and closing tags" are often referred to as "Start and end tags". Use
whatever you prefer. It is exactly the same thing.

5) XML Elements must be properly nested


In XML, all elements must be properly nested within each other:
The Following example shows correct nested tags −
<?xml version = "1.0"?>
<contact-info>
<company>TutorialsPoint</company>
</contact-info>

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 &lt; 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 -->

9) White-space is Preserved in XML


XML does not truncate multiple white-spaces (HTML truncates multiple white-
spaces to one single white-space):
XML: Hello Tove
HTML: Hello Tove

10) Well Formed XML


XML documents that conform to the syntax rules above are said to be "Well
Formed" XML documents.

 Well Formed XML Vs Valid XML documents:

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.

DIFFERENCE BETWEEN XML AND HTML

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

4.2.3: Document Type Definition (DTD)

 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.

Basic Building Blocks of XML:


Various building blocks of XML are:
1. Elements:- Basic entity is element. Elements are used for defining the
tags.

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

root element of this XML document is beginnersbook


 !ELEMENT beginnersbook defines that the root element beginnersbook must contain four
elements: “to,from,subject,message”
 !ELEMENT to defines that the element “to” is of type “#PCDATA” where “#PCDATA”
stands for Parsed Character Data which means that this data is parsable by XML parser
 !ELEMENT from defines that the element “from” is of type “#PCDATA”
 !ELEMENT subject defines that the element “subject” is of type “#PCDATA”
 !ELEMENT message defines that the element “message” is of type “#PCDATA”

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

4.2.4: XML Schema

XML schema is a language which is used for expressing constraint about


XML documents. An XML schema is used to define the structure of an XML
document. It is like DTD but provides more control on XML structure.
 XML Schema is commonly known as XML Schema Definition (XSD). It is used
to describe and validate the structure and the content of XML data.
 The XML schema language is called as XML Schema Definition (XSD)
Language.
 XML Schema defines elements, attributes, elements having child elements,
order of child elements. It also defines fixed and default values of elements
and attributes.
 XML schema also allows the developers to use data types.
 An XML document is called "well-formed" if it contains the correct syntax. A well-
formed and valid XML document is one which has been validated against Schema.
XML Schema Example
Let's create a schema file.

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>

Description of XML Schema


<xs:element name="employee"> : It defines the element name employee.
<xs:complexType> : It defines that the element 'employee' is complex type.
<xs:sequence> : It defines that the complex type is a sequence of elements.
<xs:element name="firstname" type="xs:string"/> : It defines that the element
'firstname' is of string/text type.

<xs:element name="lastname" type="xs:string"/> : It defines that the element


'lastname' is of string/text type.
<xs:element name="email" type="xs:string"/> : It defines that the element
'email' is of string/text type.

XML Schema Definition Types

You can define XML schema elements in following ways:

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>

Now let us use this type in our example as below:


<xs:element name="Address1">
<xs:complexType>
<xs:sequence>
<xs:element name="address" type="AddressType" />
<xs:element name="phone1" type="xs:int" />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="Address2">
<xs:complexType>
<xs:sequence>
<xs:element name="address" type="AddressType" />
<xs:element name="phone2" type="xs:int" />
</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.

Data Types in XML Schema


XML Schema has a lot of built-in data types. The most common types are:

 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.

ii) <xs:date> data type


 The <xs:date> data type is used to represent date in YYYY-MM-DD format.
o YYYY − represents year
o MM − represents month
o DD − represents day

iii) <xs:numeric> data type


 The <xs:decimal> data type is used to represent numeric values.
 It supports decimal numbers up to 18 digits.
 The <xs:integer> data type is used to represent integer values.

iv) <xs:boolean> data type


 The <xs:boolean> data type is used to represent true, false, 1 (for true) or 0
(for false) value.

Example

Here are some XML elements:

56
<lastname>Refsnes</lastname>
<age>36</age>
<dateborn>1970-03-27</dateborn>

And here are the corresponding simple element definitions:

<xs:element name="lastname" type="xs:string"/>


<xs:element name="age" type="xs:integer"/>
<xs:element name="dateborn" type="xs:date"/>

Default and Fixed Values for Simple Elements


 Simple elements may have a default value OR a fixed value specified.
 A default value is automatically assigned to the element when no other
value is specified.
 In the following example the default value is "red":
<xs:element name="color" type="xs:string" default="red"/>
 A fixed value is also automatically assigned to the element, and you cannot
specify another value.
 In the following example the fixed value is "red":
<xs:element name="color" type="xs:string" fixed="red"/>

Example: XML document using XML Schema

57
DIFFERENCE BETWEEN XML DTD & XML SCHEMA DEFINITION (XSD)

No. DTD XSD


DTD stands for Document Type XSD stands for XML Schema
1)
Definition. Definition.
DTDs are derived
2) XSDs are written in XML.
from SGML syntax.
XSD supports datatypes for
3) DTD doesn't support datatypes.
elements and attributes.
4) DTD doesn't support namespace. XSD supports namespace.
DTD doesn't define order for child XSD defines order for child
5)
elements. elements.
6) DTD is not extensible. XSD is extensible.
XSD is simple to learn because you
7) DTD is not simple to learn.
don't need to learn new language.
DTD provides less control on XML XSD provides more control on XML
8)
structure. structure.

58
4.2.6: XML Parsers and Validation

XML parser is a software library or a package that provides interface for


client applications to work with XML documents. 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.

Types of XML Parsers


The primary goal of any XML processor is to parse the given XML document.
Java has a rich source of built-in APIs for parsing the given XML document.
These are the two main types of XML Parsers:
1. DOM Parser (Tree based)
2. SAX Parser ( Event Based)

S.No. DOM API SAX API


1. Document Object Model Simple API for XML
2. Tree Based Parsing Event Based Parsing
The entire XML document is Part of XML document is stored
stored in memory before actual in memory. Because the parsing
processing. Hence it requires is done by generating the
3.
more memory sequence of events or by calling
handler functions. Hence it
requires less memory

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

1. DOM (Document Object Model) Parser

 A DOM document is an object which contains all the information of an XML


document. It is composed like a tree structure. The DOM Parser implements a
DOM API. This API is very simple to use.
 The DOM API is defined in the package or.w3c.dom.*
 Using this API a DOM object tree is created from the input XML document and
this tree helps in parsing the XML document.

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.*;

public class dom


{
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);
if(fp.exists())
{
try
{
DocumentBuilderFactory dbf = new DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.new DocumentBuilder();
InputSource ips = new InputSource(filename);
60
Document doc = db.parse(ips);
System.out.println(filename + “is well formed”);
}
catch(Exception e)
{
System.out.println(filename+“ isn‟t well-formed”);
System.exit(1);
}
}
else
{
System.out.println(“File not Found”);
}
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
}

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:

C:> java dom


Enter file name student1.xml
[FatalError] student1.xml:34:3: The element type “Marks” must be terminated by
the matching end-tag “</Marks>”.
Student1.xml isn‟t well-formed!

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.

2. SAX (Simple API for XML) Parser


 A SAX Parser implements SAX API. This API is an event based API and less
intuitive.
 It does not create any internal structure.
 Clients does not know what methods to call, they just overrides the methods of
the API and place his own code inside method.
 It is an event based parser, it works like an event handler in Java.

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.

EXtensible Stylesheet Language (XSL) and XSL Transformations(XSLT)

EXtensible Stylesheet Language (XSL) documents describes how an XML


document should look on the browser.

XSL is a group of three technologies:


1. XSL-FO(XSL Formatting Objects) – It is vocabulary for specifying formatting
of an XML document.
2. XPath (XML Path Language) – It is string-based language of expressions for
effectively locating specific elements and attributes in XML documents. It is used
for navigating through XML document.
66
3. XSLT (XSL Transformations) – It is a technology for transforming XML
documents into other documents; i.e., transforming the structure of the XML
document data to another structure.

 Transforming an XML document using XSLT involves two tree structures:


[1] Source Tree – the XML document to be transformed.
[2] Result Tree – the XML document to be created.
Source XML
document
XSL Transformation Resultant XML
(XSLT) Document

XSL document

Fig: Processing of XML document using XSLT

 XPath is used to locate parts of the source-tree document that match


templates defined in an XSL stylesheet.
 When a match occurs (i.e., a node matches a template), the matching template
executes and adds its result to the result tree.
 When there are no more matches, XSLT has transformed the source tree into
the result tree.
 XSLT does not analyse every node of the source tree; it selectively navigates
the source tree using XPath‟s select and match attributes.
 For XSLT to work, the source tree must be properly structured. Schemas,
DTDs and validating parsers can validate the document structure before using
XPath and XSLT.

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.

 Example: XSL Transformation


Student.xml:

<?xml version="1.0" encoding="UTF-8"?>


<?xml-stylesheet type="text/xsl" href="stud.xsl" ?>
<student-details>
<student>
<name>AAA</name>
<reg_no>1001</reg_no>
<year>1</year>
<semester>II</semester>
<grade>B</grade>
<address>chennai</address>
</student>
<student>
<name>BBB</name>
<reg_no>1002</reg_no>
<year>2</year>
<semester>III</semester>
<grade>B</grade>
<address>chennai</address>
</student>
<student>
<name>CCC</name>
<reg_no>1003</reg_no>
<year>3</year>
<semester>V</semester>
<grade>A</grade>
<address>chennai</address>
</student>
<student>
<name>DDD</name>
<reg_no>2001</reg_no>
<year>1</year>
<semester>II</semester>
<grade>A</grade>

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

<?xml version="1.0" ?>


<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body bgcolor="#ffcadd">
<center>
<h2> STUDENT DATABASE </h2>
<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>
<xsl:for-each select="student-details/student">
<xsl:sort select="grade" />
<tr bgcolor="#f0c0a0">
<td><xsl:value-of select="name" /></td>
<td><xsl:value-of select="reg_no" /></td>
<td><xsl:value-of select="year" /></td>
<td><xsl:value-of select="semester" /></td>
<td><xsl:value-of select="grade" /></td>
<td><xsl:value-of select="address" /></td>
</tr>

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>

<xsl:for-each select="student-details/student[year = 1]">


<tr bgcolor="#f0c0a0">
<td><xsl:value-of select="name"/></td>
<td><xsl:value-of select="reg_no"/></td>
<td><xsl:value-of select="year"/></td>
<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>
<hr />

<h1><center>Students with "A" Grade</center></h1>


<table border="1">
<tr bgcolor="white">
<th>Student Name</th>
<th>Register Number</th>
<th>Year</th>
<th>Semester</th>
<th>Grade</th>
<th>Address</th>
</tr>
<xsl:for-each select="student-details/student[grade = 'A']">
<tr bgcolor="#f0c0a0">
<td><xsl:value-of select="name"/></td>
<td><xsl:value-of select="reg_no"/></td>
<td><xsl:value-of select="year"/></td>

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

1. What is PHP? (NOV/DEC 2016)


Hypertext Preprocessor is an acronym for PHP. PHP is an open-source server scripting language, and
a powerful tool for creating dynamic and interactive Web pages. PHP is a widely-used, free, and efficient
alternative to competitors such as Microsoft's ASP.

2. What is a PHP file?


 PHP files can contain text, HTML, CSS, JavaScript, and PHP code
 PHP code are executed on the server, and the result is returned to the browser as plain HTML
 PHP files have extension ".php"

3. List out the features of PHP.


 PHP can generate dynamic page content
 PHP can create, open, read, write, delete, and close files on the server
 PHP can collect form data
 PHP can send and receive cookies
 PHP can add, delete, modify data in your database
 PHP can be used to control user-access
 PHP can encrypt data
 With PHP we are not limited to output HTML. we can output images, PDF files, and even Flash
movies. we can also output any text, such as XHTML and XML.

4. What are advantages of PHP?


 Used for creating dynamic and interactive web pages
 PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
 PHP is compatible with almost all servers used today (Apache, IIS, etc.)
 PHP supports a wide range of databases
 PHP is free. Download it from the official PHP resource
 PHP is easy to learn and runs efficiently on the server side

5. Write the syntax for writing PHP scripts.


A PHP script can be placed anywhere in the document.
A PHP script starts with <?php and ends with ?>:
<?php
// PHP code goes here
?>
The default file extension for PHP files is ".php".
A PHP file normally contains HTML tags, and some PHP scripting code.

6. Write the PHP script to print “Hello” message on the screen.


<!DOCTYPE html>
<html>
<body>
<h1>My first PHP page</h1>

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

72
</body>
</html>

7. How will you create variables in PHP?


Variables are "containers" for storing information.
In PHP, a variable starts with the $ sign, followed by the name of the variable:
Example:
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>

8. List the rules for creating variables in PHP.


A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume).
Rules for PHP variables:
 A variable starts with the $ sign, followed by the name of the variable
 A variable name must start with a letter or the underscore character
 A variable name cannot start with a number
 A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
 Variable names are case-sensitive ($age and $AGE are two different variables)
9. What is meant by variable scope?
The lifetime of a variable during the program execution is called the scope of a variable and it is the
part of the script where the variable can be referenced/used.
PHP has three different variable scopes:
 Local - A variable declared within a function has a LOCAL SCOPE and can only be accessed
within that function
 global - A variable declared outside a function has a GLOBAL SCOPE and can only be accessed
outside a function
 static – A variable declared inside the function with the keyword “static” and it helps to
preserve the variable even after the function execution has completed. 

10. List the various data types supported in PHP.


PHP variables are loosely typed – they can contain different types of data at different times. The
various data types supported in PHP are:
Type Description
int, integer Whole numbers (i.e., numbers without a decimal point)
float, double, real Real numbers (i.e., numbers containing a decimal point)
String Test enclosed in either single(‘ ‘) or double (“ “) quotes.
bool, boolean True or false
Array Group of elements
Object Group of associated data and methods
Resource An external resource – usually information form database
NULL No Value

11. Name some built-in functions in PHP. (NOV / DEC 2015)


 Array Functions
 Class/Object Functions
 Character Functions
 Date & Time Functions
73
 Error Handling Functions
 MySQL Functions
 ODBC Functions
 String Functions
 XML Parsing Functions

12. How will create user-defined function in PHP?


A function is a block of statements that can be used repeatedly in a program.
A function will not execute immediately when a page loads.
A function will be executed by a call to the function.
Creating User Defined Function in PHP
A user defined function declaration starts with the word "function":
Syntax
function functionName()
{
code to be executed;
}

13. What is form validation PHP? (APRIL/MAY 2021, 2022)


Form validation is a “technical process where a web-form checks if the information provided by a user
is correct.” The form will either alert the user that they messed up and need to fix something to
proceed, or the form will be validated and the user will be able to continue with their registration
process.
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.
Some of Validation rules for field:
Field Validation Rules
Name Should require letters and white-spaces
Email Should require @ and .
Website Should require a valid URL
Radio Must be selectable at least once
Check Box Must be checkable at least once
Drop Down menu Must be selectable at least once

14. Write a PHP program to add two numbers.


<html>
<head>
<title>Writing PHP Function to add Two Numbers</title>
</head>
<body>
<?php
function addFunction($num1, $num2)
{
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
addFunction(10, 20);
?>
74
</body>
</html>
Output:
Sum of the two numbers is : 30

15. Write the steps to connect a PHP program with a database.


i. Open a connection to MySQL itself - mysql_connect()
ii. Specify the database we want to open - mysql_select_db()
iii. Close the connection - mysql_close()

16. How to set cookies in PHP?


PHP provided setcookie() function to set a cookie. This function requires upto six arguments and
should be called before <html> tag. For each cookie this function has to be called separately.
Syntax: setcookie(name, value, expire, path, domain, security);
Example:

<?php
setcookie("name", "John Watkin", time()+3600, "/","", 0);
setcookie("age", "36", time()+3600, "/", "", 0);
?>

17. What is meant by Regular Expression?


Regular expressions are nothing more than a sequence or pattern of characters itself. They
provide the foundation for pattern-matching functionality.
Using regular expression we can search a particular string inside another string, we can replace
one string by another string and you can split a string into many chunks.

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

19. List some POSIX regular expression functions.


Function Description

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.

20. List some Perl compatible regular expression functions.


Function Description

The preg_match() function searches string for pattern, returning true if pattern exists,
preg_match()
and false otherwise.

preg_match_all() The preg_match_all() function matches all occurrences of pattern in string.

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.

preg_ quote() Quote regular expression characters

21. What is XML?


XML stands for Extensible Markup Language. It is a text-based markup language for describing the
format for data exchanged between applications over the internet. XML permits document authors to
create new markup languages for describing any type of data.

22. List the important characteristics of XML.


 XML is extensible: XML allows you to create your own self-descriptive tags, or language, that suits
your application.
 XML carries the data, does not present it: XML allows you to store the data irrespective of how it
will be presented.
 XML is a public standard: XML was developed by an organization called the World Wide Web
Consortium (W3C) and is available as an open standard.

23. Mention the uses (advantages) of XML.


 XML can work behind the scene to simplify the creation of HTML documents for large web
sites.
 XML can be used to exchange the information between organizations and systems.
 XML can be used for offloading and reloading of databases.
 XML can be used to store and arrange the data, which can customize your data handling needs.
 XML can easily be merged with style sheets to create almost any desired output.
 Virtually, any type of data can be expressed as an XML document.

24. What are the XML Syntax Rules?


1. The XML declaration is case sensitive and must begin with "<?xml>" where "xml" is written in
lower-case.
2. If document contains XML declaration, then it strictly needs to be the first statement of the XML
document.
76
3. ttribute names in XML (unlike HTML) are case sensitive. That is, HREF and href are considered two
different XML attributes.
4. Same attribute cannot have two values in a syntax. The following example shows incorrect syntax
because the attribute b is specified twice:
5. <a b="x" c="y" b="z">.... </a>
6. Attribute names are defined without quotation marks, whereas attribute values must always
appear in quotation marks. Following example demonstrates incorrect xml syntax:
7. <a b=x>. .. </a>
8. In the above syntax, the attribute value is not defined in quotation marks.
9. 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.
10. To avoid character encoding problems, all XML files should be saved as Unicode UTF-8 or UTF-16
files.
11. Whitespace characters like blanks, tabs and line-breaks between XML-elements and between the
XML-attributes will be ignored.
12. Some characters are reserved by the XML syntax itself. Hence, they cannot be used directly.

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>

Both highschool and medicalschool are namespace prefixes.

27. How the namespace is declared?


A Namespace is declared using reserved attributes. Such an attribute name must either be
xmlns or begin with xmlns: shown as below:
<element xmlns:name="URL">
Syntax:
 The Namespace starts with the keyword xmlns.
 The word name is the Namespace prefix. 
 The URL is the Namespace identifier.

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>

28. What is meant by Document Type Definition? (NOV/DEC 2022)


Rules that define the legal elements and attributes for XML documents are called Document Type
Definitions (DTD) or XML Schemas.
There are two different document type definitions that can be used with XML:
 DTD - The original Document Type Definition
 XML Schema - An XML-based alternative to DTD

29. What is the purpose of DTD?


The purpose of a DTD is to define the structure of an XML document. It defines the
structure with a list of legal elements:

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>

The DTD above is interpreted like this:


 !DOCTYPE note defines that the root element of the document is note
 !ELEMENT note defines that the note element must contain four elements: "to, from, heading, body"
 !ELEMENT to defines the to element to be of type "#PCDATA"
 !ELEMENT from defines the from element to be of type "#PCDATA"
 !ELEMENT heading defines the heading element to be of type "#PCDATA"
 !ELEMENT body defines the body element to be of type "#PCDATA"

30. What is meant by Internal DTD?


A DTD is referred to as an internal DTD if elements are declared within the XML files. To refer
it as internal DTD, standalone attribute in XML declaration must be set to yes. This means, the
declaration works independent of external source.
Syntax
The syntax of internal DTD is as shown:

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>

31. Give an example for External DTD.


In external DTD elements are declared outside the XML file. They are accessed by specifying the
system attributes. To refer it as external DTD, standalone attribute in the XML declaration must be set as
no. This means, declaration includes information from the external source.
Syntax:
Following is the syntax for external DTD:
<!DOCTYPE root-element SYSTEM "file-name">
where file-name is the file with .dtd extension.
Example:
The following example shows external DTD usage:
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<!DOCTYPE address SYSTEM "address.dtd">
<address>
<name>Tanmay Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 123-4567</phone>
</address>
The content of the DTD file address.dtd are as shown:
<!ELEMENT address (name,company,phone)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT company (#PCDATA)>
<!ELEMENT phone (#PCDATA)>

32. What is XML Schema? (April/May 2021)


XML Schema is commonly known as XML Schema Definition (XSD). It is used to describe and validate
the structure and the content of XML data. XML schema defines the elements, attributes and data types.
Schema element supports Namespaces. It is similar to a database schema that describes the data in a
database.

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">

Example: The following example shows how to use schema:

<?xml version="1.0" encoding="UTF-8"?>


<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="contact">
<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>
</xs:schema>
The basic idea behind XML Schemas is that they describe the legitimate format that an XML document
can take.

34. What are the data types supported by XML Schema?


Type Description Example
String A character string “hello”
Boolean True or False true
Decimal A decimal numeral 5, -12, -45.78
Float A floating-point number 0, 12, -109.75, NaN
Double A floating-point number 0, 12, -109.75, NaN
Long A whole number 1234567890, -1234567890
Int A whole number 12345, -12345
Short A whole number 12, -345
Date A date consisting of year, month and day 2005-05-10
Time A time consisting of hours, minutes and seconds 16:30:25-05:00

35. What is meant by XML DOM?


The W3C Document Object Model (DOM) is a platform and language-neutral Application Programming
Interface (API) that allows programs and scripts to dynamically access and update the content, structure,
and style of a HTML, XHTML & XML document.

36. Define DOM tree.


In XML document the information is maintained in hierarchical structure, this hierarchical
structure is referred as Node Tree or DOM Tree.

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:

37. What is meant by DOM Parser?


An XML parser that creates the DOM tree structure is known as DOM parser.
38. What is an XML Parser?
XML parser is a software library or a package that provides interface for client applications to work
with XML documents. It checks for proper format of the XML document and may also validate the XML
documents. Modern day browsers have built-in XML parsers.
Following diagram shows how XML parser interacts with XML document:

The goal of a parser is to transform XML into a readable code.

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.

40. What is meant by XML validation?


XML validation is the process of checking a document written in XML (eXtensible Markup
Language) against its specified DTD to confirm that it is both well-formed and also "valid”. When a
document fails to conform to a DTD or a schema, the validator displays an error message.

41. What is meant by well-formed XML document?


An XML document with correct syntax is "Well Formed". A well-formed XML document must follow
the following XML syntax rules:
 XML documents must have a root element
 XML elements must have a closing tag
 XML tags are case sensitive
 XML elements must be properly nested
 XML attribute values must be quote.
Example well-formed XML document:
<?xml version="1.0" encoding="UTF-8"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget to complete the work!</body>
</note>

42. What is meant by “Valid XML document”?


An XML document that contains the proper elements with the proper attributes in the proper
sequence according to the DTD specification is called a “Valid” XML document. An XML document cannot be
valid unless it is well-formed.

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)

44. Explain two types of XSL information.


An XSL document normally contains two types of information:
 Template data - Which is text that is copied to the output XML text document with little or
no change? i.e. Everything in the body of the document that is not XSL markup is template
data And
 XSL markup - which controls the transformation process always start with “xsl:”.

45. Name any four XSL elements .Mentions its use.


a. The <xsl:variable> XSL element creates a named variable.
b. The <xsl:value-of> XSL element processes a value.
c. The <xsl:if> XSL element invokes the enclosed code if the condition specified by the test
attribute is true.
d. The <xsl:sort> XSL element sorts a list of elements, such as within <xsl:for-each>.
e. The <xsl:template> XSL element encapsulates a segment of XSL code, similar to a method,
procedure, or function in other languages.
46. What is XSLT?
XSLT stands for XSL Transformations. XSLT is a language for transforming XML documents
into XHTML documents or to other XML documents. XSLT uses XPath to navigate in XML documents.
With XSLT user can add/remove elements and attributes to or from the output file.

47. What is XPath?


XPath is a language used to navigate through elements and attributes in an XML document.
 XPath is a syntax for defining parts of an XML document
 XPath uses path expressions to navigate in XML documents
 XPath contains a library of standard functions
 XPath is a major element in XSLT
 XPath is a W3C recommendation

48. How does XSLT works?


In the transformation process, XSLT uses XPath to define parts of the source document that
should match one or more predefined templates. When a match is found, XSLT will transform the
matching part of the source document into the result document.

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.

51. List the important characteristics of PHP. (NOV/DEC 2018)


o Familiarity
o Simplicity
o Efficiency
o Security
o Flexibility
o Open source
o Object Oriented

52. Explain DTD for XML Schemas. (NOV/DEC 2018)


A DTD is a Document Type Definition. A DTD defines the structure and the legal elements and
attributes of an XML document. An XML Schema describes the structure of an XML document.
XML document has a reference to a DTD.

53. Give different ways to validate a form (NOV/DEC 2022)

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

You might also like