CS8651 - IP - Notes - Unit 4
CS8651 - IP - Notes - Unit 4
What is PHP?
PHP is an acronym for "PHP: Hypertext Preprocessor"
PHP is a widely-used, open source server-side scripting language for
creating dynamic web pages.
PHP scripts are executed on the server.
PHP is platform independent and free to download and use.
HISTORY:
PHP was created by Rasmus Lerdorf to track users at his website.
In 1995, Lerdorf released it as a package called the “Personal Home Page
Tools”.
Two years later, PHP 2 features built-in database support and form
handling.
In 1997, PHP 3 was released with a rewritten parser, which substantially
increased performance and led to an explosion of PHP use.
The release of PHP 4 featured the new “Zend Engine” from Zend, a PHP
software company. This version was faster and more powerful than its
predecessor.
Currently, PHP 5 features the new “Zend Engine 2” which provides further
speed increases, exception handling and a new object-oriented
programming model.
FEATURES OF PHP:
1. PHP can generate dynamic page content.
2. PHP can create, open, read, write, delete, and close files on the server.
3. PHP can collect form data.
4. PHP can send and receive cookies.
5. PHP can add, delete, and modify data in your database.
1
CS8651- Internet Programming Unit – 4 VI Sem CSE
ADVANTAGES OF PHP:
Portability (Platform Independent) - PHP runs on various platforms
(Windows, Linux, UNIX, Mac OS X, etc.)
Performance - Scripts written in PHP executives faster than those written
in other scripting language.
Ease Of Use – It is easy to use. Its syntax is clear and consistent.
Open Source - PHP is an open source project –it may be used without
payment of licensing fees or investments in expensive hardware or
software. This reduces software development costs without affecting either
flexibility or reliability
PHP is compatible with almost all servers used today (Apache, IIS, etc.)
PHP supports a wide range of databases.
PHP is easy to learn and runs efficiently on the server side.
Community Support - One of the nice things about a community-supported
language like PHP is, accessing it offers to the creativity and imagination of
hundreds of developers across the world.
INSTALLING PHP:
To program PHP, follow the below three steps:
o install a web server (Any Web server capable of executing PHP codes)
o install PHP
o install a database, such as MySQL
The official PHP website (PHP.net) has installation instructions for PHP:
http://php.net/manual/en/install.php
2
CS8651- Internet Programming Unit – 4 VI Sem CSE
<!DOCTYPE html>
<html>
<body>
<?php
echo "Hello World!";
?>
</body>
</html>
COMMENTS IN PHP:
A comment in PHP code is a line that is not read/executed as part of the
program. Its only purpose is to be read by someone who is looking at the
code.
Comments can be used to:
Let others understand what you are doing
Remind yourself of what you did.
Example:
<!DOCTYPE html>
<html>
<body>
<?php
// This is a single-line comment
# This is also a single-line comment
/*
This is a multiple-lines comment block that
spans over Multiple lines
*/
$x = 5 /* + 15 */ + 5;
3
CS8651- Internet Programming Unit – 4 VI Sem CSE
echo $x;
?>
</body>
</html>
<?php
// all the echo statements are treated as same
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
</body>
</html>
Hello World!
Hello World!
Hello World!
My car is red
My house is
My boat is
4
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;
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:
5
CS8651- Internet Programming Unit – 4 VI Sem CSE
Global Scope:
A variable declared outside a function has a GLOBAL SCOPE and can only
be accessed outside a function:
Local Scope:
A variable declared within a function has a LOCAL SCOPE and can only be
accessed within that function.
Example:
<?php
$num1=1; // global variable
$x = 5; // global variable
$y = 10; // global variable
function myTest() {
$num1=11; // local variable
static $z=0;
$z++;
echo "z = ".$z."<br>"; // static variable retains the last changed value
global $x, $y;
$y = $x + $y;
echo "num1 inside function = ".$num1."<br>"; // prints 11
}
myTest();
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
function myTest() {
$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
}
myTest();
echo $y; // outputs 15
?>
<?php
$txt1 = "Learn PHP";
$txt2 = "deitel.com";
$x = 5;
$y = 4;
echo "<h2>$txt1</h2>";
print "Study PHP at " . $txt2 . "<br>";
Output:
Learn PHP
Study PHP at deitel.com
X+Y=9
Variables can store data of different types, and different data types can do
different things.
Type Description
string Text enclosed in either single („ „) or double (“ “) quotes.
int, Integer Whole numbers (i.e., numbers without a decimal point)
float, double, real Real numbers (i.e., numbers containing a decimal point)
bool, boolean True or False
array Group of elements
8
CS8651- Internet Programming Unit – 4 VI Sem CSE
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
PHP Resource:
The special resource type is not an actual data type.
It is the storing of a reference to functions and resources external to PHP.
A common example of using the resource data type is a database call.
<!DOCTYPE html>
<html>
<body>
<?php
$x = 5985; // Integer variable
$y = 59.85; // float variable
$str1="Hello "; // string
$str2="World"; // string
$bool1=true; // boolean
$bool2=false; // boolean
$cars = array("Volvo","BMW","Toyota"); // array
<?php
10
CS8651- Internet Programming Unit – 4 VI Sem CSE
// create an object
$herbie = new Car(); // creating object for car class
Output:
Example:
<!DOCTYPE html>
<html>
<body>
<?php
$var1="114";
$var2=114.12;
$var3=114;
settype($var1,"double");
settype($var2,"integer");
settype($var3,"string");
?>
</body>
</html>
12
CS8651- Internet Programming Unit – 4 VI Sem CSE
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
?>
</body>
</html>
14
CS8651- Internet Programming Unit – 4 VI Sem CSE
15
CS8651- Internet Programming Unit – 4 VI Sem CSE
Example:
<html>
<head><title>Logical Operators</title><head>
16
CS8651- Internet Programming Unit – 4 VI Sem CSE
<body>
<?php
$x=10;
$y=5;
?>
</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
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:
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>";
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:
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
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
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();
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
);
25
CS8651- Internet Programming Unit – 4 VI Sem CSE
3. Multidimensional Arrays
A multi-dimensional array each element in the main array can also be an
array.
Each element in the sub-array can be an array, and so on.
Values in the multi-dimensional array are accessed using multiple index.
<html>
<body>
<?php
$marks = array(
"AAA" => array
( "physics" => 35,
"maths" => 30,
"chemistry" => 39 ),
26
CS8651- Internet Programming Unit – 4 VI Sem CSE
</body>
</html>
Output:
4.1.9: FUNCTIONS
Definition: A function is a piece of code which takes one or more input in the
form of parameter and does some processing and returns a value.
Creating functions:
Example:
<html>
<head>
<title>Writing PHP Function with Parameters</title>
</head>
<body>
27
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";
}
</body>
</html>
Output:
Sum of the two numbers is : 30
function addSix(&$num)
{
$num += 6;
}
$orignum = 10;
addFive( $orignum );
28
CS8651- Internet Programming Unit – 4 VI Sem CSE
addSix( $orignum );
echo "Original Value is $orignum<br />";
?>
</body>
</html>
<?php
function addFunction($num1, $num2)
{
$sum = $num1 + $num2;
return $sum;
}
$return_value = addFunction(10, 20);
</body>
</html>
29
CS8651- Internet Programming Unit – 4 VI Sem CSE
<!DOCTYPE html>
<html>
<body>
<?php
function setHeight($minheight = 50) {
echo "The height is : $minheight <br>";
}
setHeight(350);
setHeight(); // this function call will use the default value „50‟
setHeight(135);
setHeight(80);
?>
</body>
</html>
Output:
The height is : 350
The height is : 50
The height is : 135
The height is : 80
30
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
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
}
}
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>";
</body>
</html>
Output:
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
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.
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>";
37
CS8651- Internet Programming Unit – 4 VI Sem CSE
Form: A Document that containing black fields, that the user can fill the data or
user can select the data.
What is Validation?
Validation means check the input submitted by the user.
There are two types of validation are available in PHP. They are as follows −
Client-Side Validation − Validation is performed on the client machine web
browsers.
Server Side Validation − After submitted by data, The data has sent to a
server and perform validation checks in server machine.
The PHP superglobals $_GET and $_POST are used to collect form-data.
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.
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";
}
?>
39
CS8651- Internet Programming Unit – 4 VI Sem CSE
<?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
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.
Syntax
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.
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
$fp = fopen('data.txt', 'w');//opens file in write-only mode
fwrite($fp, 'welcome ');
fwrite($fp, 'to php file write');
fclose($fp);
Output: data.txt
welcome to php file write
Example
<?php
$fp = fopen('data.txt', 'a');//opens file in append mode
fwrite($fp, ' this is additional text ');
fwrite($fp, 'appending data');
fclose($fp);
Output: data.txt
welcome to php file write this is additional text appending data
<?php
$status=unlink('data.txt');
if($status){
echo "File deleted successfully";
}else{
echo "Sorry!";
}
?>
Output:
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.
Only the name parameter is required. All other parameters are optional.
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.
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];
}
?>
</body>
</html>
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>
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
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
In this chapter, we will discuss the simple syntax rules to write an XML
document. Following is a complete XML document −
You can notice there are two kinds of information in the above example −
Markup, like <contact-info>
The text, or the character data, Tutorials Point and (040) 123-4567.
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.
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.
<element>....</element>
or in simple-cases, just this way −
<element/>
Root Element − An XML document can have only one root element. For
example, following is not a correct XML document, because both
the x and y elements occur at the top level without a root element −
<x>...</x>
<y>...</y>
The Following example shows a correctly formed XML document −
<root>
<x>...</x>
<y>...</y>
</root>
XML Attributes
An attribute specifies a single property for the element, using a name/value
pair. An XML-element can have one or more attributes. For example −
<a href = "http://www.abc.com/">abc Tutorial!</a>
Here href is the attribute name and http://www.abc.com/ is attribute value.
56
CS8651- Internet Programming Unit – 4 VI Sem CSE
XML References
References usually allow you to add or include additional text or markup in an
XML document. References always begin with the symbol "&" which is a
reserved character and end with the symbol ";". XML has two types of references
−
Entity References − An entity reference contains a name between the
start and the end delimiters. For example & where amp is name.
The name refers to a predefined string of text and/or markup.
Character References − These contain references, such as A,
contains a hash mark (“#”) followed by a number. The number always
refers to the Unicode code of a character. In this case, 65 refers to
alphabet "A".
XML Text
The names of XML-elements and XML-attributes are case-sensitive, which
means the name of start and end elements need to be written in the same
case. To avoid character encoding problems, all XML files should be saved as
Unicode UTF-8 or UTF-16 files.
Whitespace characters like blanks, tabs and line-breaks between XML-
elements and between the XML-attributes will be ignored.
Some characters are reserved by the XML syntax itself. Hence, they cannot be
used directly. To use them, some replacement-entities are used, which are
listed below –
Not Allowed Character Replacement Entity Character Description
57
CS8651- Internet Programming Unit – 4 VI Sem CSE
58
CS8651- Internet Programming Unit – 4 VI Sem CSE
7) Entity References
Some characters have a special meaning in XML.
If you place a character like "<" inside an XML element, it will generate an error
because the parser interprets it as the start of a new element.
This will generate an XML error:
<message>salary < 1000</message>
To avoid this error, replace the "<" character with an entity reference:
<message>salary < 1000</message>
8) Comments in XML
The syntax for writing comments in XML is similar to that of HTML:
<!-- This is a comment -->
Two dashes in the middle of a comment are not allowed:
<!-- This is an invalid -- comment -->
Well Formed XML documents: XML documents that conform to the syntax
rules above are said to be "Well Formed" XML documents.
Valid XML Document:
If an XML document conforms to its DTD/Schema that defines the proper
structure of the document, then the XML document is valid XML document.
59
CS8651- Internet Programming Unit – 4 VI Sem CSE
XML HTML
Software and hardware independent Software and hardware dependent
To send and store data To display data
Focus on what data is present Focus on how data looks
It is a Framework for markup language
It is a markup language
definition
Case sensitive Case insensitive
Transport data between app and database Design client side web programs
Custom tags allowed Only predefined tags
Open and close tags are strict Not strict
White space insensitive White space insensitive
Carry information Display information
Dynamic Static
DTD stands for Document Type Definition. An XML DTD defines the
structure of an XML document.
XML DTD is used to define the basic building block of any XML
document. Using DTD, we can specify the various element types,
attributes, and their relationships with one another.
XML DTD is used to specify the set of rules for structuring data in any
XML file.
An XML document is considered “well formed” and “valid” if it is
successfully validated against DTD.
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
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>
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>
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.
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.
Example
66
CS8651- Internet Programming Unit – 4 VI Sem CSE
<lastname>Refsnes</lastname>
<age>36</age>
<dateborn>1970-03-27</dateborn>
67
CS8651- Internet Programming Unit – 4 VI Sem CSE
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
DOM Tree:
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).
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:-
71
CS8651- Internet Programming Unit – 4 VI Sem CSE
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
XML parser validates the document and check that the document is well
formatted.
72
CS8651- Internet Programming Unit – 4 VI Sem CSE
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.*;
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:
Advantages
1) It supports both read and write operations and the API is very simple to use.
2) It is preferred when random access to widely separated parts of a document is
required.
Disadvantages
1) It is memory inefficient. (Consumes more memory because the whole XML
document needs to loaded into memory).
2) It is comparatively slower than other parsers.
Example: Checking the Well Formedness of XML document using SAX API.
import java.io.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
public class Parsing_SAXDemo
{
public static void main(String bala[])
{
try
{
System.out.println(“Enter XML document name”);
BufferedReader input = new BufferedReader( new InputStreamReader(System.in));
String filename = input.readLine();
File fp = new File(filename);
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.
XSL document
XSL Elements:
Elements Description
<xsl:template> Contains rules to apply when a
specified node is matched. The
“match” attribute is associated with
this element. The match= “/” defines
the whole document.
<xsl:value-of select = “expression”> Selects the value of an XML element
and adds it to the output tree. The
select attribute contains an XPath
expression.
<xsl:for-each select = “expression”> Applies a template to every node
selected by the XPath expression.
<xsl:sort select = “expression”> Sorts the nodes selected by <<xsl:for-
80
CS8651- Internet Programming Unit – 4 VI Sem CSE
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
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>
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
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.
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
RSS Example
RSS documents use a self-describing and simple syntax.
Here is a simple RSS document:
<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.
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.
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
<?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:-
<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