0% found this document useful (0 votes)
192 views

CS8651 - IP - Notes - Unit 4

Uploaded by

J. MEENA
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)
192 views

CS8651 - IP - Notes - Unit 4

Uploaded by

J. MEENA
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/ 90

CS8651- Internet Programming Unit – 4 VI Sem CSE

UNIT IV PHP and XML


An introduction to PHP: PHP- Using PHP- Variables- Program control- Built-
in functions- Form Validation- Regular Expressions - File handling –
Cookies - Connecting to Database. XML: Basic XML- Document Type
Definition- XML Schema DOM and Presenting XML, XML Parsers and
Validation, XSL and XSLT Transformation, News Feed (RSS and ATOM)
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
CS8651- Internet Programming Unit – 4 VI Sem CSE

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
CS8651- Internet Programming Unit – 4 VI Sem CSE

 "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
CS8651- Internet Programming Unit – 4 VI Sem CSE

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.1.3: PHP – VARIABLES

Definition: Variables are "containers" for storing information.

4
CS8651- Internet Programming Unit – 4 VI Sem CSE

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

5
CS8651- Internet Programming Unit – 4 VI Sem CSE

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

6
CS8651- Internet Programming Unit – 4 VI Sem CSE

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
CS8651- Internet Programming Unit – 4 VI Sem CSE

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
CS8651- Internet Programming Unit – 4 VI Sem CSE

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
CS8651- Internet Programming Unit – 4 VI Sem CSE

 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
CS8651- Internet Programming Unit – 4 VI Sem CSE

// 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
CS8651- Internet Programming Unit – 4 VI Sem CSE

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
CS8651- Internet Programming Unit – 4 VI Sem CSE

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
CS8651- Internet Programming Unit – 4 VI Sem CSE

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
CS8651- Internet Programming Unit – 4 VI Sem CSE

 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
CS8651- Internet Programming Unit – 4 VI Sem CSE

 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
CS8651- Internet Programming Unit – 4 VI Sem CSE

<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
CS8651- Internet Programming Unit – 4 VI Sem CSE

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
CS8651- Internet Programming Unit – 4 VI Sem CSE

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
CS8651- Internet Programming Unit – 4 VI Sem CSE

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
CS8651- Internet Programming Unit – 4 VI Sem CSE

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
CS8651- Internet Programming Unit – 4 VI Sem CSE

 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
CS8651- Internet Programming Unit – 4 VI Sem CSE

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++) {
echo "The number is: $x <br>"; The number is: 1
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
CS8651- Internet Programming Unit – 4 VI Sem CSE

<?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
CS8651- Internet Programming Unit – 4 VI Sem CSE

$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
CS8651- Internet Programming Unit – 4 VI Sem CSE

/* 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
CS8651- Internet Programming Unit – 4 VI Sem CSE

/* 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
CS8651- Internet Programming Unit – 4 VI Sem CSE

<?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
CS8651- Internet Programming Unit – 4 VI Sem CSE

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
CS8651- Internet Programming Unit – 4 VI Sem CSE

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
CS8651- Internet Programming Unit – 4 VI Sem CSE

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
CS8651- Internet Programming Unit – 4 VI Sem CSE

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
CS8651- Internet Programming Unit – 4 VI Sem CSE

}
}

$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
CS8651- Internet Programming Unit – 4 VI Sem CSE

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
CS8651- Internet Programming Unit – 4 VI Sem CSE

</body>
</html>

Output:

4.1.11: REGULAR EXPRESSIONS

Regular Expressions: are series of characters that serve as pattern-


matching templates in strings, text files and database.

Two sets of regular expression functions:


[1] POSIX (Portable Operating System Interface Extended) Regular Expressions
[2] PERL-Compatible Regular Expressions (PCRE)

 POSIX Regular Expressions:

Brackets
Brackets ([]) have a special meaning when used in the context of regular
expressions. They are used to find a range of characters.

Expression Description
[0-9] It matches any decimal digit from 0 through 9.
[a-z] It matches any character from lower-case a through lowercase z.
[A-Z] It matches any character from uppercase A through uppercase Z.
[a-Z] It matches any character from lowercase a through uppercase Z.

Quantifiers
Expression Description
p+ It matches any string containing at least one p.
p* It matches any string containing zero or more p's.
p? It matches any string containing zero or more p's. This is just an
alternative way to use p*.
p{N} It matches any string containing a sequence of N p's
p{2,3} It matches any string containing a sequence of two or three p's.
p{2, } It matches any string containing a sequence of at least two p's.
p$ It matches any string with p at the end of it.
35
CS8651- Internet Programming Unit – 4 VI Sem CSE

^p It matches any string with p at the beginning of it.

Examples
Following examples will clear your concepts about matching characters.
Expression Description
[^a-zA-Z] It matches any string not containing any of the characters
ranging from a through z and A through Z.
p.p It matches any string containing p, followed by any character, in
turn followed by another p.
^.{2}$ It matches any string containing exactly two characters.
<b>(.*)</b> It matches any string enclosed within <b> and </b>.
p(hp)* It matches any string containing a p followed by zero or more
instances of the sequence php.

Predefined Character Ranges


Expression Description
[[:alpha:]] It matches any string containing alphabetic characters aA
through zZ.
[[:digit:]] It matches any string containing numerical digits 0 through 9.
[[:alnum:]] It matches any string containing alphanumeric characters aA
through zZ and 0 through 9.
[[:space:]] It matches any string containing a space.
[[:<:]] bracket expression matches the beginning of a word
[[:>:]] bracket expression matches the end of a word
[[:upper:]] matches single uppercase character
[[:lower:]] matches single lower case character
[:upper:] matches all uppercase strings
[:lower:} matches all lowercase strings

PHP's Regexp POSIX Functions

PHP currently offers seven functions for searching strings using POSIX-style
regular expressions

Function Description
ereg() The ereg() function searches a string specified by pattern,
returning true if the pattern is found, and false otherwise.
ereg_replace() The ereg_replace() function searches for string specified by
pattern and replaces pattern with replacement if found.
eregi() The eregi() function searches a string specified by pattern by
ignoring case.
eregi_replace() The eregi_replace() function operates exactly like
ereg_replace(), except that the search for pattern in string is
not case sensitive.
split() The split() function will divide a string into various elements,
the boundaries of each element based on the occurrence of
36
CS8651- Internet Programming Unit – 4 VI Sem CSE

pattern in string.
spliti() The spliti() function operates exactly in the same manner as
its sibling split(), except that it is not case sensitive.

Example:

<!DOCTYPE html>
<html>
<head>
<title> PHP - Regular Expressions </title>
</head>
<body>
<?php
$str="I like PHP programming";
echo "Test String is <b>".$str."</b><br>";

// call ereg to search for pattern "PHP"


if(eregi("php", $str))
echo "String PHP found <br/>";

// search for the string that ends with 'ing'


$res=ereg("[[:alpha:]]+ing",$str,$value);
if($res==true)
echo "String that end with ing is :".$value[0]."<br>" ;

//validate the given phone no


$phone="1234567890";
if(ereg("[0-9]{10}",$phone))
print("Given phone number ".$phone." is valid");
else
print("Given phone number ".$phone." is invalid");
?>
</body>
</html>

37
CS8651- Internet Programming Unit – 4 VI Sem CSE

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.

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

38
CS8651- Internet Programming Unit – 4 VI Sem CSE

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

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>

39
CS8651- Internet Programming Unit – 4 VI Sem CSE

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>

Output:

40
CS8651- Internet Programming Unit – 4 VI Sem CSE

4.1.13: PHP FILE HANDLING

PHP File System allows us to create file, read file line by line, read file
character by character, write file, append file, delete file and close file.

 PHP Open File - fopen()


 PHP fopen() function is used to open file or URL and returns resource.
 The fopen() function accepts two arguments: $filename and $mode.
 The $filename represents the file to be opended and $mode represents the
file mode for example read-only, read-write, write-only etc.

Syntax

resource fopen ( string $filename , string $mode [, bool $use_include_path = false [,


resource $context ]] )

PHP Open File Mode


Mode Description
r Opens file in read-only mode. It places the file pointer at the beginning
of the file.
r+ Opens file in read-write mode. It places the file pointer at the beginning
of the file.
w Opens file in write-only mode. It places the file pointer to the beginning
of the file and truncates the file to zero length. If file is not found, it
creates a new file.
w+ Opens file in read-write mode. It places the file pointer to the beginning
of the file and truncates the file to zero length. If file is not found, it
creates a new file.
a Opens file in write-only mode. It places the file pointer to the end of the
file. If file is not found, it creates a new file.
a+ Opens file in read-write mode. It places the file pointer to the end of the
file. If file is not found, it creates a new file.
x Creates and opens file in write-only mode. It places the file pointer at
41
CS8651- Internet Programming Unit – 4 VI Sem CSE

the beginning of the file. If file is found, fopen() function returns FALSE.
x+ It is same as x but it creates and opens file in read-write mode.
c Opens file in write-only mode. If the file does not exist, it is created. If it
exists, it is neither truncated (as opposed to 'w'), nor the call to this
function fails (as is the case with 'x'). The file pointer is positioned on
the beginning of the file
c+ It is same as c but it opens file in read-write mode.

 PHP Read File


 PHP provides various functions to read data from file.
 There are different functions that allow you to read all file data, read data
line by line and read data character by character.
 The available PHP file read functions are given below.
1) fread() –
 It is used to read data of the file. It requires two arguments: file
resource and file size.
 Syntax: string fread(resource $handle, int $length)
$handle – represents file pointer that is created by fopen() function
$length – represents length of byte to be read
Example:
<?php
$filename = "c:\\file1.txt";
$fp = fopen($filename, "r");//open file in read mode

$contents = fread($fp, filesize($filename));//read file

echo "<pre>$contents</pre>";//printing data of file


fclose($fp);//close file
?>
Output:
this is first line
this is another line
this is third line

2) fgets() –
 It is used to read single line from the file.
 Syntax: string fgets(resource $handle [, int $length] )
Example;
<?php
$fp = fopen("c:\\file1.txt", "r");//open file in read mode
echo fgets($fp);
fclose($fp);
?>
42
CS8651- Internet Programming Unit – 4 VI Sem CSE

Output:
this is first line

3) fgetc() –
 It is used to read single character from the file.
 To get all data using fgetc() function, use !feof() function inside the
while loop.
 Syntax: string fgetc(resource $handle)
Example:

<?php
$fp = fopen("c:\\file1.txt", "r");//open file in read mode
while(!feof($fp)) {
echo fgetc($fp);
}
fclose($fp);
?>
Output:
this is first line this is another line this is third line

 PHP Write File


 PHP fwrite() and fputs() functions are used to write data into file.
 To write data into file, you need to use w, r+, w+, x, x+, c or c+ mode.
1) fwrite() –
 It is used to write content of the string into file.
 Syntax: int fwrite(resource $handle, string $string [, int $length] )
Example

<?php
$fp = fopen('data.txt', 'w');//opens file in write-only mode
fwrite($fp, 'welcome ');
fwrite($fp, 'to php file write');
fclose($fp);

echo "File written successfully";


?>

Output: data.txt
welcome to php file write

 PHP Append to File


You can append data into file by using a or a+ mode in fopen() function. Let's
see a simple example that appends data into data.txt file.
43
CS8651- Internet Programming Unit – 4 VI Sem CSE

Example

<?php
$fp = fopen('data.txt', 'a');//opens file in append mode
fwrite($fp, ' this is additional text ');
fwrite($fp, 'appending data');
fclose($fp);

echo "File appended successfully";


?>

Output: data.txt
welcome to php file write this is additional text appending data

 PHP Delete File


 In PHP, we can delete any file using unlink() function. The unlink() function
accepts one argument only: file name. It is similar to UNIX C unlink()
function.
 PHP unlink() generates E_WARNING level error if file is not deleted. It
returns TRUE if file is deleted successfully otherwise FALSE.
 Syntax: bool unlink ( string $filename [, resource $context ] )
 Example:

<?php
$status=unlink('data.txt');
if($status){
echo "File deleted successfully";
}else{
echo "Sorry!";
}
?>

Output:

File deleted successfully

44
CS8651- Internet Programming Unit – 4 VI Sem CSE

4.1.14: Cookies
PHP cookie is a small piece of information which is stored at client
browser. It is used to recognize the user.
 Cookie is created at server side and saved to client browser. Each time when
client sends request to the server, cookie is embedded with request. Such
way, cookie can be received at the server side.
 They are typically used to keeping track of information such as username
that the site can retrieve to personalize the page when user visit the website
next time.
 Each time the browser requests a page to the server, all the data in the cookie
is automatically sent to the server within the request.

 Uses of Cookies
 Session management: Cookies are widely used to manage user sessions.
For example, when you use an online shopping cart, you keep adding items
in the cart and finally when you checkout, all of those items are added to
the list of items you have purchased. This can be achieved using cookies.
 User identification: Once a user visits a webpage, using cookies, that user
can be remembered. And later on, depending upon the search/visit pattern
of the user, content which the user likely to be visited are served. A good
example of this is 'Retargetting'. A concept used in online marketing, where
depending upon the user's choice of content, advertisements of the relevant
product, which the user may buy, are served.
 Tracking / Analytics: Cookies are used to track the user. Which, in turn,
is used to analyze and serve various kind of data of great value, like
location, technologies (e.g. browser, OS) form where the user visited, how
long (s)he stayed on various pages etc.

 How to create/Access a cookie in PHP?


Setting a Cookie in PHP
The setcookie() function is used to set a cookie in PHP. Make sure you call the
setcookie() function before any output generated by your script otherwise
cookie will not set. The basic syntax of this function can be given with:

setcookie(name, value, expire, path, domain, secure);

Only the name parameter is required. All other parameters are optional.

The parameters of the setcookie() function have the following meanings:

45
CS8651- Internet Programming Unit – 4 VI Sem CSE

Parameter Description
name The name of the cookie.
value The value of the cookie. Do not store sensitive information since
this value is stored on the user's computer.
expires The expiry date in UNIX timestamp format. After this time cookie
will become inaccessible. The default value is 0.
path Specify the path on the server for which the cookie will be
available. If set to /, the cookie will be available within the entire
domain.
domain Specify the domain for which the cookie is available to e.g
www.example.com.
secure This field, if present, indicates that the cookie should be sent only
if a secure HTTPS connection exists.

Accessing Cookies Values


 The PHP $_COOKIE superglobal variable is used to retrieve a cookie value.
 It typically an associative array that contains a list of all the cookies values
sent by the browser in the current request, keyed by cookie name.
 The individual cookie value can be accessed using standard array notation.

Example:
The following example creates a cookie named "user" with the value "John
Doe". The cookie will expire after 30 days (86400 * 30).
The "/" means that the cookie is available in entire website (otherwise, select
the directory you prefer).
We then retrieve the value of the cookie "user" (using the global variable
$_COOKIE). We also use the isset() function to find out if the cookie is set:

<!DOCTYPE html>
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); //
86400 = 1 day
?>
<html>
<body>

<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
46
CS8651- Internet Programming Unit – 4 VI Sem CSE

} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>

<p><strong>Note:</strong> You might have to reload the page to see the


value of the cookie.</p>

</body>
</html>

Modify a Cookie Value

To modify a cookie, just set (again) the cookie using the setcookie() function:

Example
<?php
$cookie_name = "user";
$cookie_value = "Alex Porter";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>
<html>
<body>

<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>

</body>
</html>

Delete a Cookie
To delete a cookie, use the setcookie() function with an expiration date in
the past:

Example
47
CS8651- Internet Programming Unit – 4 VI Sem CSE

<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
<html>
<body>

<?php
echo "Cookie 'user' is deleted.";
?>

</body>
</html>

Check if Cookies are Enabled


The following example creates a small script that checks whether cookies are
enabled. First, try to create a test cookie with the setcookie() function, then
count the $_COOKIE array variable:

Example
<?php
setcookie("test_cookie", "test", time() + 3600, '/');
?>
<html>
<body>

<?php
if(count($_COOKIE) > 0) {
echo "Cookies are enabled.";
} else {
echo "Cookies are disabled.";
}
?>

</body>
</html>

48
CS8651- Internet Programming Unit – 4 VI Sem CSE

4.1.15: Connecting Database

49
CS8651- Internet Programming Unit – 4 VI Sem CSE

50
CS8651- Internet Programming Unit – 4 VI Sem CSE

51
CS8651- Internet Programming Unit – 4 VI Sem CSE

52
CS8651- Internet Programming Unit – 4 VI Sem CSE

53
CS8651- Internet Programming Unit – 4 VI Sem CSE

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.

54
CS8651- Internet Programming Unit – 4 VI Sem CSE

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 −
55
CS8651- Internet Programming Unit – 4 VI Sem CSE

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

56
CS8651- Internet Programming Unit – 4 VI Sem CSE

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

57
CS8651- Internet Programming Unit – 4 VI Sem CSE

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

58
CS8651- Internet Programming Unit – 4 VI Sem CSE

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.

59
CS8651- Internet Programming Unit – 4 VI Sem CSE

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.
60
CS8651- Internet Programming Unit – 4 VI Sem CSE

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”

61
CS8651- Internet Programming Unit – 4 VI Sem CSE

62
CS8651- Internet Programming Unit – 4 VI Sem CSE

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

63
CS8651- Internet Programming Unit – 4 VI Sem CSE

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:
64
CS8651- Internet Programming Unit – 4 VI Sem CSE

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

65
CS8651- Internet Programming Unit – 4 VI Sem CSE

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

66
CS8651- Internet Programming Unit – 4 VI Sem CSE

<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

67
CS8651- Internet Programming Unit – 4 VI Sem CSE

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.

4.2.5: DOM and Presenting XML

DoM:-
 Document Object Model
 The Document Object Model (DOM) is a W3C standard
 The DOM defines a standard for accessing and manipulating documents.
 The XML DOM presents an XML document as a tree- structure.
 The HTML DOM presents an HTML document as a tree- structure.

68
CS8651- Internet Programming Unit – 4 VI Sem CSE

 "The W3C Document Object Model (DOM) is a platform and language-neutral


interface that allows programs and scripts to dynamically access and update
the content, structure, and style of a document."

The DOM is separated into 3 different parts / levels:


 Core DOM - standard model for any structured document
 XML DOM - standard model for XML documents
 HTML DOM - standard model for HTML documents

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

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

69
CS8651- Internet Programming Unit – 4 VI Sem CSE

<zip>07670</zip>
</address>
</person>
</addresses>
The following tree of element nodes represents this document:

Example:-

<?xml version="1.0"?>
<userdata>
<user1>
<userno>001</userno>
<username>Bala</username>
<phonenumber>123456789</phonenumber>
<address>Chennai</address>
</user1>
<user2>
<userno>002</userno>
<username>Suresh</username>
<phonenumber>987654321</phonenumber>
<address>madurai</address>
</user2>
<user3>
<userno>003</userno>
<username>arul</username>
<phonenumber>1122334455</phonenumber>
<address>Vellore</address>
</user3>
</userdata>

70
CS8651- Internet Programming Unit – 4 VI Sem CSE

user.html

<!DOCTYPE html>
<html>
<body>
<script>
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","student.xml",false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
var x=xmlDoc.documentElement.childNodes;
document.write("<table border='1'>");
for(var i=0;i<x.length;i++)
{
document.write("<tr>”);
document.write("<td>"+ xmlDoc.getElementsByTagName("userno")[i].childNodes[0].nodeValue+"</td>");
document.write("<td>"+xmlDoc.getElementsByTagName("username")[i].childNodes[0].nodeValue+"</td>");
document.write("<td>"+xmlDoc.getElementsByTagName("phonenumber")[i].childNodes[0].nodeValue+"</td>");
document.write("<td>"+xmlDoc.getElementsByTagName("address")[i].childNodes[0].nodeValue+"</td>");
document.write("</tr>");
}
document.write("</table>");
</script>
</body>
</html>

O/P:-

001 Bala 123456789 Chennai


002 Suresh 987654321 madurai
003 arul 1122334455 Vellore

71
CS8651- Internet Programming Unit – 4 VI Sem CSE

 xmlDoc - the XML DOM object created by the parser.


 getElementsByTagName("title")[0] - get the first <title> element
 childNodes[0] - the first child of the <title> element (the text node)
 nodeValue - the value of the node (the text itself)

XML DOM Properties


These are some typical DOM properties:
 x.nodeName - the name of x
 x.nodeValue - the value of x
 x.parentNode - the parent node of x
 x.childNodes - the child nodes of x
 x.attributes - the attributes nodes of x

XML DOM Methods


 x.getElementsByTagName(name) - get all elements with a specified tag
name
 x.appendChild(node) - insert a child node to x
 x.removeChild(node) - remove a child node from x

DOM Nodes
 The entire document is a document node
 Every XML element is an element node
 The text in the XML elements are text nodes
 Every attribute is an attribute node
 Comments are comment nodes

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.

72
CS8651- Internet Programming Unit – 4 VI Sem CSE

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
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.
73
CS8651- Internet Programming Unit – 4 VI Sem CSE

 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);
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”);
}

74
CS8651- Internet Programming Unit – 4 VI Sem CSE

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

Output:
C:> javac dom.java
C:> java dom
Enter file name dom.xml
dom.xml is well formed

Program Explanation:

75
CS8651- Internet Programming Unit – 4 VI Sem CSE

76
CS8651- Internet Programming Unit – 4 VI Sem CSE

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

77
CS8651- Internet Programming Unit – 4 VI Sem CSE

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:

78
CS8651- Internet Programming Unit – 4 VI Sem CSE

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.

4.2.7: XSL and XSLT Transformation


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.
79
CS8651- Internet Programming Unit – 4 VI Sem CSE

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-

80
CS8651- Internet Programming Unit – 4 VI Sem CSE

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>

81
CS8651- Internet Programming Unit – 4 VI Sem CSE

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

82
CS8651- Internet Programming Unit – 4 VI Sem CSE

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

83
CS8651- Internet Programming Unit – 4 VI Sem CSE

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

84
CS8651- Internet Programming Unit – 4 VI Sem CSE

4.2.8: News Feeds (RSS and ATOM)

 On the World Wide Web, a web feed (or news feed) is a data format used for
providing users with frequently updated content.
 A web feed is a document (often XML-based) whose discrete content items
include web links to the source of the content.
 News websites and blogs are common sources for web feeds, but feeds are also
used to deliver structured information ranging from weather data to top-ten
lists of hit tunes to search results.
 The two main web feed formats are RSS and Atom.
 Web feeds are designed to be machine-readable rather than human-readable
 This means that web feeds can also be used to automatically transfer
information from one website to another without any human intervention.

Advantages of Web feeds


 Users do not disclose their email address when subscribing to a feed and so are
not increasing their exposure to threats associated with email: spam, viruses,
phishing, and identity theft.
 Users do not have to send an unsubscribe request to stop receiving news. They
simply remove the feed from their aggregator.
 The feed items are automatically sorted in that each feed URL has its own sets
of entries (unlike an email box where messages must be sorted by user-defined
rules and pattern matching)

RSS
(Rich Site Summary or RDF Site Summary or Really Simple Syndication)

RSS stand for: It depends on what version of RSS you are using.
• RSS Version 0.9 - Rich Site Summary
• RSS Version 1.0 - RDF Site Summary
• RSS Versions 2.0, 2.0.1, and 0.9x - Really Simple Syndication

 What is RSS?
 RSS allows you to syndicate your site content
 RSS defines an easy way to share and view headlines and content
 RSS files can be automatically updated
 RSS allows personalized views for different sites
 RSS is written in XML

 Why use RSS?


85
CS8651- Internet Programming Unit – 4 VI Sem CSE

 RSS was designed to show selected data.


 Without RSS, users will have to check your site daily for new updates. This
may be too time-consuming for many users. With an RSS feed (RSS is often
called a News feed or RSS feed) they can check your site faster using an
RSS aggregator (a site or program that gathers and sorts out RSS feeds).
 Since RSS data is small and fast-loading, it can easily be used with
services like cell phones or PDA's.
 Web-rings with similar information can easily share data on their web sites
to make them better and more useful.

 Who Should use RSS?


 Webmasters who seldom update their web sites do not need RSS!
 RSS is useful for web sites that are updated frequently, like:
 News sites - Lists news with title, date and descriptions
 Companies - Lists news and new products
 Calendars - Lists upcoming events and important days
 Site changes - Lists changed pages or new pages

 How RSS Works?


 RSS is used to share content between websites.
 With RSS, you register your content with companies called aggregators.
 So, to be a part of it: First, create an RSS document and save it with an
.xml extension. Then, upload the file to your website. Next, register with an
RSS aggregator. Each day the aggregator searches the registered websites
for RSS documents, verifies the link, and displays information about the
feed so clients can link to documents that interest them.

 RSS Example
RSS documents use a self-describing and simple syntax.
Here is a simple RSS document:

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


<rss version="2.0">

<channel>
<title>W3Schools Home Page</title>
<link>https://www.w3schools.com</link>
<description>Free web building tutorials</description>
<item>
<title>RSS Tutorial</title>
<link>https://www.w3schools.com/xml/xml_rss.asp</link>
<description>New RSS tutorial on W3Schools</description>

86
CS8651- Internet Programming Unit – 4 VI Sem CSE

</item>
<item>
<title>XML Tutorial</title>
<link>https://www.w3schools.com/xml</link>
<description>New XML tutorial on W3Schools</description>
</item>
</channel>
</rss>

 The first line in the document - the XML declaration - defines the XML
version and the character encoding used in the document. In this case the
document conforms to the 1.0 specification of XML and uses the UTF-8
character set.

 The next line is the RSS declaration which identifies that this is an RSS
document (in this case, RSS version 2.0).
 The next line contains the <channel> element. This element is used to
describe the RSS feed.
 The <channel> element has three required child elements:
 <title> - Defines the title of the channel (e.g. W3Schools Home Page)
 <link> - Defines the hyperlink to the channel (e.g. https://www.w3schools.com)
 <description> - Describes the channel (e.g. Free web building tutorials)
 Each <channel> element can have one or more <item> elements.
 Each <item> element defines an article or "story" in the RSS feed.
 The <item> element has three required child elements:
 <title> - Defines the title of the item (e.g. RSS Tutorial)
 <link> - Defines the hyperlink to the item
(e.g. https://www.w3schools.com/xml/xml_rss.asp)
 <description> - Describes the item (e.g. New RSS tutorial on W3Schools)
 Finally, the two last lines close the <channel> and <rss> elements.

Advantages for Subscribers

RSS subscribers are the people who subscribe to read a published Feed

1. All news at one place: You can subscribe to multiple news groups and
then you can customize your reader to have all the news on a single page.
It will save you a lot of time.
2. News when you want it: Rather than waiting for an e-mail, you go to your
RSS reader when you want to read a news. Furthermore, RSS Feeds
display more quickly than information on web-sites, and you can read
them offline if you prefer.
87
CS8651- Internet Programming Unit – 4 VI Sem CSE

3. Get the news you want: RSS Feed comes in the form of headlines and a
brief description so that you can easily scan the headlines and click only
those stories that interest you.
4. Freedom from e-mail overload: You are not going to get any email for any
news or blog update. You just go to your reader and you will find updated
news or blog automatically whenever there is a change on the RSS server.
5. Easy Republishing: You may be both subscriber and a publisher. For
example, you may have a web-site that collects news from various other
sites and then republishes it. RSS allows you to easily capture that news
and display it on your site.

Advantages for Publishers


RSS publishers are the people who publish their content through RSS feed.
1. Easier publishing: RSS is really simple publishing. You don't have to
maintain a database of subscribers to send your information to them;
instead they will access your Feed using a reader and will get updated
content automatically.
2. A simpler writing process: If you have a new content on your web site,
you only need to write an RSS Feed in the form of titles and short
descriptions, and link back to your site.
3. An improved relationship with your subscribers: Because people
subscribe from their side, they don't feel as if you are pushing your content
on them.
4. The assurance of reaching your subscribers: RSS is not subject to spam
filters, your subscribers get the Feeds, which they subscribe to and nothing
more.
5. Links back to your site: RSS Feeds always include links back to a
website. It directs a lot of traffic towards your website.
6. Relevance and timeliness: Your subscribers always have the latest
information from your site.

ATOM
 Atom is the name of an XML-based Web content and metadata syndication
format, and an application-level protocol for publishing and editing Web
resources belonging to periodically updated websites.
 Atom is a relatively recent spec and is much more robust and feature-rich
than RSS.
 For instance, where RSS requires descriptive fields such as title and link only
in item breakdowns, Atom requires these things for both items and the full
Feed.
 All Atom Feeds must be well-formed XML documents, and are identified with
the application/atom+xml media type.

88
CS8651- Internet Programming Unit – 4 VI Sem CSE

Structure of an Atom 1.0 Feed

<?xml version="1.0"?>
<feed xmlns="http://www.w3.org/2005/Atom">
<title>...</title>
<link>...</link>
<updated>...</updated>

<author>
<name>...</name>
</author>

<id>...</id>

<entry>
<title>...</title>
<link>...</link>
<id>...</id>

<updated>...</updated>
<summary>...</summary>
</entry>

</feed>

Example:-

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


<feed xmlns="http://www.w3.org/2005/Atom">

<title>Example Feed</title>
<subtitle>Insert witty or insightful remark here</subtitle>
<link href="http://example.org/"/>
<updated>2003-12-13T18:30:02Z</updated>
<author>
<name>Mohtashim</name>
<email>[email protected]</email>
</author>

<id>urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6</id>

89
CS8651- Internet Programming Unit – 4 VI Sem CSE

<entry>
<title>Tutorial on Atom</title>
<link href="http://example.org/2003/12/13/atom03"/>

<id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id>
<updated>2003-12-13T18:30:02Z</updated>
<summary>Some text.</summary>
</entry>
</feed>

RSS ATOM
Contains either plain text or escaped Contains html, xml, dhtml,
sequence as payload documents, audio, video, etc as
payload
Shows timestamp of data when feed Shows timestamp of data when it
was last created or updated as last updated
Uses blogger and meta weblog It has only one standard protocols
protocols
Loose approach on data Strict approach on data
More complicated process Easier process
Not a standard feature Standard feature
Less robust, scalable, efficient More robust, scalable, efficient

90

You might also like