Professional Documents
Culture Documents
Ip Unit Iv
Ip Unit Iv
TEXT BOOK:
1.Deitel and Deitel and Nieto, ―Internet and World Wide Web - How to Program‖, Prentice Hall,
5th Edition, 2011.
REFERENCES:
1.Stephen Wynkoop and John Burke ―Running a Perfect Website‖, QUE, 2nd Edition,1999.
2.Chris Bates, Web Programming – Building Intranet Applications, 3rd Edition, Wiley
Publications, 2009.
3.Jeffrey C and Jackson, ―Web Technologies A Computer Science Perspective‖, Pearson
Education, 2011.
4.Gopalan N.P. and Akilandeswari J., ―Web Technology‖, Prentice Hall of India, 2011.
5.UttamK.Roy, ―Web Technologies‖, Oxford University Press, 2011.
1
4.1 PHP: INTRODUCTION TO PHP-USING PHP
PHP started out as a small open source project that evolved as more and more people
found out how useful it was. Rasmus Lerdorf unleashed the first version of PHP way back in
1994.
PHP is a server side scripting language that is embedded in HTML. It is used to manage
dynamic content, databases, session tracking, even build entire e-commerce sites.
PHP is pleasingly zippy in its execution, especially when compiled as an Apache module
on the Unix side. The MySQL server, once started, executes even very complex queries
with huge result sets in record-setting time.
PHP supports a large number of major protocols such as POP3, IMAP, and LDAP.
PHP4 added support for Java and distributed object architectures (COM and CORBA),
making n-tier development a possibility for the first time.
PHP performs system functions, i.e. from files on a system it can create, open, read,
write, and close them.
PHP can handle forms, i.e. gather data from files, save data to a file, through email you
can send data, return data to the user.
You add, delete, modify elements within your database through PHP.
Using PHP, you can restrict users to access some pages of your website.
Characteristics of PHP
Simplicity
Efficiency
Security
2
Flexibility
Familiarity
To get a feel for PHP, first start with simple PHP scripts. Since "Hello, World!" is an
essential example, first we will create a friendly little "Hello, World!" script.
<html>
<head>
<title>Hello World</title>
</head>
<body>
</body>
</html>
Output
Hello, World!
If you examine the HTML output of the above example, you'll notice that the PHP code is
not present in the file sent from the server to your Web browser.
All of the PHP present in the Web page is processed and stripped from the page; the
only thing returned to the client from the Web server is pure HTML output.
All PHP code must be included inside one of the three special markup tags ATE are
recognised by the PHP Parser.
4.2 VARIABLES
3
The main way to store information in the middle of a PHP program is by using a variable.
Here are the most important things to know about variables in PHP.
All variables in PHP are denoted with a leading dollar sign ($).
Variables are assigned with the = operator, with the variable on the left-hand side and
the expression to be evaluated on the right.
Variables in PHP do not have intrinsic types - a variable does not know in advance
whether it will be used to store a number or a string of characters.
PHP does a good job of automatically converting types from one to another when
necessary.
PHP has a total of eight data types which we use to construct our variables −
Resources − are special variables that hold references to resources external to PHP
(such as database connections).
The first five are simple types, and the next two (arrays and objects) are compound - the
compound types can package up other arbitrary values of arbitrary type, whereas the simple
types cannot.
4.2.1 Integers
4
They are whole numbers, without a decimal point, like 4195. They are the simplest
type .they correspond to simple whole numbers, both positive and negative. Integers can be
assigned to variables, or they can be used in expressions, like so −
$int_var = 12345;
Integer can be in decimal (base 10), octal (base 8), and hexadecimal (base 16) format.
Decimal format is the default, octal integers are specified with a leading 0, and hexadecimals
have a leading 0x.
For most common platforms, the largest integer is (2**31 . 1) (or 2,147,483,647), and the
smallest (most negative) integer is . (2**31 . 1) (or .2,147,483,647).
4.2.2 Doubles
They like 3.14159 or 49.1. By default, doubles print with the minimum number of decimal
places needed. For example, the code −
<?php
$many = 2.2888800;
$many_2 = 2.2111200;
?>
Output
4.2.3 Boolean
They have only two possible values either true or false. PHP provides a couple of
constants especially for use as Booleans: TRUE and FALSE, which can be used like so −
if (TRUE)
else
5
The rules for determine the "truth" of any value not already of the Boolean type −
If the value is a number, it is false if exactly equal to zero and true otherwise.
If the value is a string, it is false if the string is empty (has zero characters) or is the
string "0", and is true otherwise.
If the value is an array, it is false if it contains no other values, and it is true otherwise.
For an object, containing a value means having a member variable that has been
assigned a value.
Valid resources are true (although some functions that return resources when they are
successful will return FALSE when unsuccessful).
Each of the following variables has the truth value embedded in its name when it is used in a
Boolean context.
$true_num = 3 + 0.14159;
$false_array = array();
$false_null = NULL;
$false_str = "";
4.2.5 NULL
NULL is a special type that only has one value: NULL. To give a variable the NULL
value, simply assign it like this −
$my_var = NULL;
$my_var = null;
A variable that has been assigned NULL has the following properties −
6
It returns FALSE when tested with IsSet() function.
4.2.6 Strings
They are sequences of characters, like "PHP supports string operations". Following are
valid examples of string
Singly quoted strings are treated almost literally, whereas doubly quoted strings replace
variables with their values as well as specially interpreting certain character sequences.
<?php
$variable = "name";
print($literally);
print "<br>";
print($literally);
?>
Output
There are no artificial limits on string length - within the bounds of available memory, you
ought to be able to make arbitrarily long strings.
Strings that are delimited by double quotes (as in "this") are preprocessed in both the
following two ways by PHP −
Certain character sequences beginning with backslash (\) are replaced with special
characters
Variable names (starting with $) are replaced with string representations of their values.
7
The escape-sequence replacements are −
Scope can be defined as the range of availability a variable has to the program in which
it is declared. PHP variables can be one of four scope types −
Local variables
Function parameters
Global variables
Static variables
A variable name can consist of numbers, letters, underscores but you cannot use
characters like + , - , % , ( , ) . & , etc
if...else statement − use this statement if you want to execute a set of code when a
condition is true and another if the condition is not true
elseif statement − is used with the if...else statement to execute a set of code if one of
the several condition is true
8
switch statement − is used if you want to
select one of many blocks of code to be
executed, use the Switch statement. The
switch statement is used to avoid long blocks
of if..elseif..else code.
if (condition)
else
Example
The following example will output "Have a nice weekend!" if the current day is Friday,
Otherwise, it will output "Have a nice day!":
<html>
<body>
<?php
$d = date("D");
if ($d == "Fri")
else
?>
</body>
</html>
Output
9
Have a nice weekend!
If you want to execute some code if one of the several conditions are true use the elseif
statement
Syntax
if (condition)
elseif (condition)
else
Example
The following example will output "Have a nice weekend!" if the current day is Friday,
and "Have a nice Sunday!" if the current day is Sunday. Otherwise, it will output "Have a nice
day!" −
<html>
<body>
<?php
$d = date("D");
if ($d == "Fri")
else
?>
</body>
</html>
10
Output:
If you want to select one of many blocks of code to be executed, use the Switch
statement.The switch statement is used to avoid long blocks of if..elseif..else code.
Syntax
switch (expression){
case label1:
break;
case label2:
break;
default:
code to be executed
if expression is different
Example
<html>
<body>
<?php
$d = date("D");
switch ($d){
case "Mon":
11
echo "Today is Monday";
break;
case "Tue":
break;
case "Wed":
break;
case "Thu":
break;
case "Fri":
break;
case "Sat":
break;
case "Sun":
break;
default:
?>
</body>
</html>
Output:
Today is Monday
12
4.3.2 Looping Statements
Loops in PHP are used to execute the same block of code a specified number of times.
PHP supports following four loop types.
while − loops through a block of code if and as long as a specified condition is true.
do...while − loops through a block of code once, and then repeats the loop as long as a
special condition is true.
The for statement is used when you know how many times you want to execute a
statement or a block of statements.
Syntax
code to be executed;
The initializer is used to set the start value for the counter of the number of loop
iterations. A variable may be declared here
for this purpose and it is traditional to name
it $i.
Example
<html>
<body>
$a = 0;
$b = 0;
$a += 10;
13
$b += 5;
?>
</body>
</html>
Output:
The while statement will execute a block of code if and as long as a test expression is
true.
If the test expression is true then the code block will be executed.
After the code has executed the test expression will again be evaluated and the loop will
continue until the test expression is found to be
false.
Syntax
while (condition) {
code to be executed;
Example
<html>
<body>
<?php
$i = 0;
$num = 50;
14
$num--;
$i++;
?>
</body>
</html>
Output
The do...while statement will execute a block of code at least once - it then will repeat
the loop as long as a condition is true.
Syntax
do {
code to be executed;
while (condition);
Example
The following example will increment the value of i at least once, and it will continue
incrementing the variable i as long as it has a value of less than 10 −
<html>
<body
<?php
$i = 0;
$num = 0;
do {
$i++;
while( $i < 10 );
15
echo ("Loop stopped at i = $i" );
?>
</body>
</html>
Output:
Loop stopped at i = 10
Syntax
code to be executed;
Example
<html>
<body>
<?php
?>
</body>
</html>
Output:
Value is 1
Value is 2
Value is 3
16
Value is 4
Value is 5
Example
In the following example condition test becomes true when the counter value reaches 3
and loop terminates.
<html>
<body>
<?php
$i = 0;
$i++;
if( $i == 3 )break;
?>
</html>
Output:
Loop stopped at i = 3
The PHP continue keyword is used to halt the current iteration of a loop but it does not
terminate the loop.
Just like the break statement the continue statement is situated inside the statement
block containing the code that the loop executes, preceded by a conditional test.
For the pass encountering continue statement, rest of the loop code is skipped and next
pass starts.
17
Example
In the following example loop prints the value of array but for which condition becomes
true it just skip the code and next value is printed.
<html>
<body>
<?php
?>
</html>
Output:
Value is 1
Value is 2
Value is 4
Value is 5
PHP function is a piece of code that can be reused many times. It can take input as
argument list and return value. There are thousands of built-in functions in PHP.
In PHP, we can define Conditional function, Function within
Function and Recursive function also.
Code Reusability: PHP functions are defined only once and can be invoked many
times, like in other programming languages.
Less Code: It saves a lot of code because you don't need to write the logic many times.
By the use of function, you can write the logic only once and reuse it.
18
Easy to understand: PHP functions separate the programming logic. So it is easier to
understand the flow of the application because every logic is divided in the form of
functions.
Syntax
function functionname(){
//code to be executed
}
Note: Function name must be start with letter and underscore only like other labels in PHP. It
can't be start with numbers or special symbols.
File: function1.php
<?php
function sayHello(){
echo "Hello PHP Function";
}
sayHello();//calling function
?>
Output:
Example
File: functionarg.php
<?php
function sayHello($name){
19
echo "Hello $name<br/>";
}
sayHello("Sonoo");
sayHello("Vimal");
sayHello("John");
?>
Output:
Hello Sonoo
Hello Vimal
Hello John
Example
File: functionarg2.php
<?php
function sayHello($name,$age){
echo "Hello $name, you are $age years old<br/>";
}
sayHello("Sonoo",27);
sayHello("Vimal",29);
sayHello("John",23);
?>
Output:
Value passed to the function doesn't modify the actual value by default (call by value).
But we can do so by passing value as a reference.
By default, value passed to the function is call by value. To pass value as a reference,
you need to use ampersand (&) symbol before the argument name.
20
Example:
File: functionref.php
<?php
function adder(&$str2)
{
$str2 .= 'Call By Reference';
}
$str = 'Hello ';
adder($str);
echo $str;
?>
Output:
We can specify a default argument value in function. While calling PHP function if you
don't specify any argument, it will take the default argument. Let's see a simple example
of using default argument value in PHP function.
File: functiondefaultarg.php
<?php
function sayHello($name="Sonoo"){
echo "Hello $name<br/>";
}
sayHello("Rajesh");
sayHello();//passing no value
sayHello("John");
?>
Output:
Hello Rajesh
Hello Sonoo
21
Hello John
Example:
File: functiondefaultarg.php
<?php
function cube($n){
return $n*$n*$n;
}
echo "Cube of 3 is: ".cube(3);
?>
Output:
Cube of 3 is: 27
* required field
Name: *
E-mail: *
Website:
Comment:
Submit
Input:
22
Field Validation Rules
Name Required. + Must only contain letters and whitespace
E-mail Required. + Must contain a valid email address (with @
and .)
Website Optional. If present, it must contain a valid URL
Comment Optional. Multi-line input field (textarea)
Gender Required. Must select one
4.5.1 Text Fields
The name, email, and website fields are text input elements, and the comment field is a
textarea. The HTML code looks like this:
The gender fields are radio buttons and the HTML code looks like this:
Gender:
When the form is submitted, the form data is sent with method="post".
The $_SERVER["PHP_SELF"] is a super global variable that returns the filename of the
currently executing script.
So, the $_SERVER["PHP_SELF"] sends the submitted form data to the page itself,
instead of jumping to a different page. This way, the user will get error messages on the
same page as the form.
23
The htmlspecialchars() function converts special characters to HTML entities. This
means that it will replace HTML characters like < and > with < and >. This prevents
attackers from exploiting the code by injecting HTML or Javascript code (Cross-site
Scripting attacks) in forms.
Now, if a user enters the normal URL in the address bar like
"http://www.example.com/test_form.php", the above code will be translated to:
However, consider that a user enters the following URL in the address bar:
http://www.example.com/test_form.php/%22%3E%3Cscript%3Ealert('hacked')%3C/script%3E
This code adds a script tag and an alert command. And when the page loads, the
JavaScript code will be executed (the user will see an alert box). This is just a simple
and harmless example how the PHP_SELF variable can be exploited.
Be aware of that any JavaScript code can be added inside the <script> tag! A hacker
can redirect the user to a file on another server, and that file can hold malicious code
that can alter the global variables or submit the form to another address to save the user
data, for example.
The htmlspecialchars() function converts special characters to HTML entities. Now if the
user tries to exploit the PHP_SELF variable, it will result in the following output:
24
<formmethod="post" action="test_form.php/"><script>alert('hacked')</
script>">
The first thing we will do is to pass all variables through PHP's htmlspecialchars()
function.
When we use the htmlspecialchars() function; then if a user tries to submit the following
in a text field:
<script>location.href('http://www.hacked.com')</script>
- this would not be executed, because it would be saved as HTML escaped code, like this:
<script>location.href('http://www.hacked.com')</script>
Example
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$gender = test_input($_POST["gender"]);
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
25
?>
Regular expressions are nothing more than a sequence or pattern of characters itself.
They provide the foundation for pattern-matching functionality.
Using regular expression you can search a particular string inside a another string, you
can replace one string by another string and you can split a string into many chunks.
PHP offers functions specific to two sets of regular expression functions, each corre-
sponding to a certain type of regular expression. You can use any of them based on
your comfort.
POSIX Regular Expressions
PERL Style Regular Expressions
Brackets ([]) have a special meaning when used in the context of regular expressions. They
are used to find a range of characters.
The frequency or position of bracketed character sequences and single characters can
be denoted by a special character. Each special character having a specific connota-
tion. The +, *, ?, {int. range}, and $ flags all follow a character sequence.
Sr.N
Expression & Description
o
26
1 p+ It matches any string containing at least one p.
Examples
Sr.N
Expression & Description
o
It matches any string not containing any of the characters
1 [^a-zA-Z]
ranging from a through z and A through Z.
It matches any string containing p, followed by any charac-
2 p.p ter, in turn followed by another p.
It matches any string containing exactly two characters.
3 ^.{2}$
For your programming convenience several predefined character ranges, also known
as character classes, are available. Character classes specify an entire range of char-
acters, for example, the alphabet or an integer set –
27
[[:alpha:]] It matches any string containing alphabetic characters aA
1
through zZ.
28
PERL Style Regular Expressions
Perl-style regular expressions are similar to their POSIX counterparts. The POSIX syn-
tax can be used almost interchangeably with the Perl-style regular expression func-
tions. In fact, you can use any of the quantifiers introduced in the previous POSIX sec-
tion.
Meta characters
Several modifiers are available that can make your work with regexps much easier, like
case sensitivity, searching in multiple lines etc.
Modifier Description
i Makes the match case insensitive
m Specifies that if the string has newline or carriage
return characters, the ^ and $ operators will now
match against a newline boundary, instead of a
string boundary
29
o Evaluates the expression only once
s Allows use of . to match a newline character
x Allows you to use white space in the expression for clarity
g Globally finds all matches
cg Allows a search to continue even after a global match fails
Opening a file
Reading a file
Writing a file
Closing a file
The PHP fopen() function is used to open a file. It requires two arguments stating first
the file name and then mode in which to operate.
Files modes can be specified as one of the six options in this table.
If an attempt to open a file fails then fopen returns a value of false otherwise it returns a
file pointer which is used for further reading or writing to that file.
30
After making a changes to the opened file it is important to close it with the fclose()
function. The fclose() function requires a file pointer as its argument and then returns
true when the closure succeeds or false if it fails.
Once a file is opened using fopen() function it can be read with a function called fread().
This function requires two arguments. These must be the file pointer and the length of
the file expressed in bytes.
The files length can be found using the filesize() function which takes the file name as its
argument and returns the size of the file expressed in bytes.
So here are the steps required to read a file with PHP.
Open a file using fopen() function.
Get the file's length using filesize() function.
Read the file's content using fread() function.
Close the file with fclose() function.
The following example assigns the content of a text file to a variable then displays those
contents on the web page.
<html>
<head>
</head>
<body>
<?php
$filename = "tmp.txt";
exit();
fclose( $file );
echo ( "<pre>$filetext</pre>" );
31
?>
</body>
</html>
Output:
A new file can be written or text can be appended to an existing file using the PHP
fwrite() function.
This function requires two arguments specifying a file pointer and the string of data that
is to be written.
Optionally a third integer argument can be included to specify the length of the data to
write. If the third argument is included, writing would will stop after the specified length
has been reached.
The following example creates a new text file then writes a short text heading inside it.
After closing this file its existence is confirmed using file_exist() function which takes file
name as an argument
<?php
$filename = "/home/user/guest/newfile.txt";
exit();
fclose( $file );
?>
<html>
<head>
32
<title>Writing a file using PHP</title>
</head>
<body>
<?php
$filename = "newfile.txt";
exit();
fclose( $file );
echo ( "$filetext" );
?>
</body>
</html>
Output:
4.8 COOKIES
Cookies are text files stored on the client computer and they are kept of use tracking
purpose. PHP transparently supports HTTP cookies.
There are three steps involved in identifying returning users −
Server script sends a set of cookies to the browser. For example name, age, or
identification number etc.
Browser stores this information on local machine for future use.
33
When next time browser sends any request to web server then it sends those
cookies information to the server and server uses that information to identify the
user.
Cookies are usually set in an HTTP header (although JavaScript can also set a cookie
directly on a browser). A PHP script that sets a cookie might send headers that look
something like this −
HTTP/1.1 200 OK
path=/; domain=tutorialspoint.com
Connection: close
Content-Type: text/html
The Set-Cookie header contains a name value pair, a GMT date, a path and a domain.
The name and value will be URL encoded.
The expires field is an instruction to the browser to "forget" the cookie after the given
time and date.
If the browser is configured to store cookies, it will then keep this information until the
expiry date.
If the user points the browser at any page that matches the path and domain of the
cookie, it will resend the cookie to the server.The browser's headers might look
something like this −
GET / HTTP/1.0
Connection: Keep-Alive
Host: zink.demon.co.uk:1126
Accept-Encoding: gzip
Accept-Language: en
Accept-Charset: iso-8859-1,*,utf-8
Cookie: name=xyz
34
A PHP script will then have access to the cookie in the environmental variables
$_COOKIE or $HTTP_COOKIE_VARS[] which holds all cookie names and values.
Above cookie can be accessed using $HTTP_COOKIE_VARS["name"].
<?php
?>
<html>
<head>
</head>
<body>
35
<?php echo "Set Cookies"?>
</body>
</html>
PHP provides many ways to access cookies. Simplest way is to use either $_COOKIE or
$HTTP_COOKIE_VARS variables. Following example will access all the cookies set in
above example.
<html>
<head>
</head>
<body>
<?php
/* is equivalent to */
/* is equivalent to */
?>
</body>
</html>
<html>
<head>
</head>
<body>
<?php
36
if( isset($_COOKIE["name"]))
else
?> </body>
</html>
Officially, to delete a cookie you should call setcookie() with the name argument only but
this does not always work well, however, and should not be relied on.
It is safest to set the cookie with a date that has already expired −
<?php
?>
<html>
<head>
</head>
<body>
</body>
</html>
o mysqli_connect()
o PDO::__construct()
37
PHP mysqli_connect() function is used to connect with MySQL database. It returns
resource if connection is established or null.
Syntax
PHP mysqli_close() function is used to disconnect with MySQL database. It returns true
if connection is closed or false.
Syntax
Example
<?php
$host = 'localhost:3306';
$user = '';
$pass = '';
if(! $conn )
mysqli_close($conn);
?>
Output:
Connected successfully
38
The XML Document Type Declaration, commonly known as DTD, is a way to describe
XML language precisely. DTDs check vocabulary and validity of the structure of XML
documents against grammatical rules of appropriate XML language.
An XML DTD can be either specified inside the document, or it can be kept in a separate
document and then liked separately.
Syntax
declaration1
declaration2
........
]>
A DTD is referred to as an internal DTD if elements are declared within the XML files.
To refer it as internal DTD, standalone attribute in XML declaration must be set to yes.
This means, the declaration works independent of an external source.
Syntax
where root-element is the name of root element and element-declarations is where you
declare the elements.
Example
39
<?xml version = "1.0" encoding = "UTF-8" standalone = "yes" ?>
<!DOCTYPE address [
]>
<address>
<name>Tanmay Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 123-4567</phone>
</address>
Start Declaration − Begin the XML declaration with the following statement.
DTD − Immediately after the XML header, the document type declaration follows,
commonly referred to as the DOCTYPE −
<!DOCTYPE address [
The DOCTYPE declaration has an exclamation mark (!) at the start of the element
name. The DOCTYPE informs the parser that a DTD is associated with this XML
document.
DTD Body − The DOCTYPE declaration is followed by body of the DTD, where you
declare elements, attributes, entities, and notations.
Several elements are declared here that make up the vocabulary of the <name>
document. <!ELEMENT name (#PCDATA)> defines the element name to be of type
"#PCDATA". Here #PCDATA means parse-able text data.
40
End Declaration − Finally, the declaration section of the DTD is closed using a closing
bracket and a closing angle bracket (]>). This effectively ends the definition, and
thereafter, the XML document follows immediately.
Rules
The document type declaration must appear at the start of the document (preceded only
by the XML header) − it is not permitted anywhere else within the document.
Similar to the DOCTYPE declaration, the element declarations must start with an
exclamation mark.
The Name in the document type declaration must match the element type of the root
element.
In external DTD elements are declared outside the XML file. They are accessed by
specifying the system attributes which may be either the legal .dtd file or a valid URL. To
refer it as external DTD, standalone attribute in the XML declaration must be set as no.
This means, declaration includes information from the external source.
Syntax
Example
<address>
<name>Tanmay Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 123-4567</phone>
</address>
41
<!ELEMENT phone (#PCDATA)>
4.11.3 Types
System Identifiers
A system identifier enables you to specify the location of an external file containing DTD
declarations. Syntax is as follows −
Public Identifiers
Public identifiers provide a mechanism to locate DTD resources and is written as follows
Syntax
Example
<xs:complexType>
<xs:sequence>
42
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
The basic idea behind XML Schemas is that they describe the legitimate format that an
XML document can take.
Elements
Elements are the building blocks of XML document. An element can be defined within an
XSD as follows −
Definition Types
Simple Type
Simple type element is used only in the context of the text. Some of the predefined
simple types are: xs:integer, xs:boolean, xs:string, xs:date. For example −
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 −
<xs:complexType>
<xs:sequence>
</xs:sequence>
</xs:complexType>
</xs:element>
43
In the above example, Address element consists of child elements. This is a container
for other <xs:element> definitions, that allows to build a simple hierarchy of elements in the XML
document.
Global Types
With the 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 follows −
<xs:complexType>
<xs:sequence>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:complexType>
<xs:sequence>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:complexType>
<xs:sequence>
44
</xs:sequence>
</xs:complexType>
</xs:element>
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.
Attributes
The Document Object Model (DOM) is the foundation of XML. XML documents have a
hierarchy of informational units called nodes; DOM is a way of describing those nodes
and the relationships between them.
A DOM document is a collection of nodes or pieces of information organized in a
hierarchy. This hierarchy allows a developer to navigate through the tree looking for
specific information. Because it is based on a hierarchy of information, the DOM is said
to be tree based.
The XML DOM, on the other hand, also provides an API that allows a developer to add,
edit, move, or remove nodes in the tree at any point in order to create an application.
Example
<!DOCTYPE html>
<html>
<body>
<div>
45
</div>
<script>
if (window.XMLHttpRequest)
else
xmlhttp.open("GET","/xml/address.xml",false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
document.getElementById("name").innerHTML=
xmlDoc.getElementsByTagName("name")[0].childNodes[0].nodeValue;
document.getElementById("company").innerHTML=
xmlDoc.getElementsByTagName("company")[0].childNodes[0].nodeValue;
document.getElementById("phone").innerHTML=
xmlDoc.getElementsByTagName("phone")[0].childNodes[0].nodeValue;
</script>
</body>
</html>
<contact-info>
<name>Tanmay Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 123-4567</phone>
</contact-info>
46
4.13 XML PARSER AND VALIDATION
XML parser is a software library or a package that provides interface for client applica-
tions to work with XML documents. It checks for proper format of the XML document
and may also validate the XML documents. Modern day browsers have built-in XML
parsers.
Following diagram shows how XML parser interacts with XML document −
47
Each of its opening tags must have a closing tag or it must be a self ending tag.
(<title>....</title> or <title/>).It must have only one attribute in a start tag, which
needs to be quoted.
amp(&), apos(single quote), gt(>), lt(<), quot(double quote) entities other than
these must be declared.
Example
<!DOCTYPE address
]>
<address>
<name>Tanmay Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 123-4567</phone>
</address>
Each of the child elements among name, company and phone is enclosed in its self
explanatory tag.
48
4.14 XSL AND XSLT TRANSFORMATION
In case of HTML document, tags are predefined such as table, div, and span; and the
browser knows how to add style to them and display those using CSS styles.
But in case of XML documents, tags are not predefined. In order to understand and style
an XML document, World Wide Web Consortium (W3C) developed XSL which can act
as XML based Stylesheet Language. An XSL document specifies how a browser should
render an XML document.
What is XSLT?
XSLT, Extensible Stylesheet Language Transformations, provides the ability to trans-
form XML data from one format to another automatically.
How XSLT Works?
An XSLT stylesheet is used to define the transformation rules to be applied on the tar-
get XML document. XSLT stylesheet is written in XML format.
XSLT Processor takes the XSLT stylesheet and applies the transformation rules on the
target XML document and then it generates a formatted document in the form of XML,
HTML, or text format.
This formatted document is then utilized by XSLT formatter to generate the actual out-
put which is to be displayed to the end-user.
49
Advantages:
<rss version='2.0'>
<channel>
<title>Title of Webpage</title>
<link>Webpage URL</link>
<description>About Webpage</description>
<language>en-us</language>
<item>
<title>Article Title</title>
<link>Article URL</link>
<description>Article Content</description>
</item>
</channel>
</rss>
50