0% found this document useful (0 votes)
18 views98 pages

Unit 4

Web tech unit 4

Uploaded by

hprasathoff935
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)
18 views98 pages

Unit 4

Web tech unit 4

Uploaded by

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

Dr.A.

Thomas Paul Roy


Professor, Dept. of CSE., Unit 4
PSNACET PHP & XML

Syllabus
PHP
Introduction
Program control
Connecting to databases
Cookies & Regular expressions
XML
DTD, Schema & Presenting XML
Parsers & Validation
XSL & XSLT
RSS - ATOM

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
PHP
Key points to be remembered
Synonym
Features
Prehistory
Tools required
Why PHP
What one can do?

PHP
Key points to be remembered
Stands for:
Personal Home Page
PHP: Hypertext Preprocessor

It is a “Open Source Server Side Scripting


Language” using which dynamic and
interactive webpages can be generated

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
PHP
Features
Server side scripting language
Capable to handle database driven
websites
Easier to manipulate than other languages
Can be embedded within HTML to impart
dynamism
Can be used:
To read / write files
To send emails

PHP
Prehistory
Released in 1994 by “Rasmus Lerdof”

Initially used as web publishing Macros and


subsequently developed as “Open Source”

First version released in 1995 as “PHP”

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
PHP
Prehistory

PHP / FI

PHP 3

PHP 4

PHP
Prehistory

Release Description
PHP • Used as macros
PHP / FI • PHP Form Interpreter
• Embed with HTML
• Database interactivity
PHP 3 • Developed by Suraski and Gutmans
• Created parser for PHP – that converts
from one to other that the interpreter can
understand
• Can interoperate with Apache, MySQL for
development

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
PHP
Prehistory

Release Description
PHP 4 • Recent version
• Can use with Apache, MySQL at no cost

PHP
Features of PHP 4
Easy to create objects
Supports FTP / SMTP & COM / DCOM
support
Supports Java / XML
Easy to configure “php.ini” for web
services
Supports encryption using “mcrypt” library
and has hash encryption, Triple DES, MD5,
Blowfish, SHA1
Include a PCRE library

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
PHP
Tools needed
Web browser
IE, Mozilla Fire fox
Web server
TomCat from Apache (JSP, Servlets,
PHP)
XAMPP (PHP, MySQL, PERL)
IIS
Database server
MySQL, Oracle, Sybase etc.,

PHP
Why PHP?
Runs on various platforms (Windows,
Linux, Unix, Mac OS X, etc.)
Compatible with almost all servers
(Apache, IIS, etc.)
Supports a wide range of databases
It is free – Download it from the official PHP
resource: www.php.net
Easy to learn and runs efficiently on the
server side

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
PHP
Key points to be remembered
PHP has the built in support to Apache and
MySQL Functions

PHP = {HTML, CSS, JavaScript, PHP Code}

PHP code will be executed on the server


and the result is returned back to client as
HTML

Store the file as “.php” extension

PHP
What you can do?
Using PHP, one can:
1. generate dynamic page content
2. create, open, read, write, delete, and
close files on the server
3. collect form data
4. send and receive cookies
5. add, delete, modify data in your
database
6. used to control user-access
7. can encrypt data

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
PHP
Embedding PHP in HTML
3 ways
At runtime, PHP parser
<?.....?> reads PHP file and
separate it from HTML

<?php …. ?>

<script language=“php”>
::::
</script>

PHP
Skeleton

<HTML>
<HEAD>
<TITLE>…</TITLE>
</HEAD>
<BODY>
<?php
‘—PHP Code—’
?>
</BODY>
</HTML>

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
PHP
To display the content
Use “echo” statement
<HTML>
<HEAD>
<TITLE>…</TITLE>
</HEAD>
<BODY>
<?php
echo “Third CSE A”;
?>
</BODY>
</HTML>

PHP
Commenting PHP
4 ways
Comment Description
<!– put here--> HTML Comment

// put here Single line comment

#put here Shell style comment

/* … put…*/ Multi line comment

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
PHP
Variables
Used to hold the data
1. Declare it using “$” sign preceding the
variable name
2. Can start with underscore or with letter
3. Case sensitive

Example:
$name = “ramu”;

PHP
Key points to be remembered
To display the data as output in the screen,
3 ways can be used
1. echo or echo()
2. print or print()
3. print_r()

10

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
PHP
Key points to be remembered
To display the data as output in the screen,
3 ways can be used
1. echo or echo()
2. print or print()
3. print_r()
Language construct that accepts any arguments and
returns no value / void

PHP
Key points to be remembered
To display the data as output in the screen,
3 ways can be used
1. echo or echo()
2. print or print()
3. print_r()
it is a language construct but always returns the value 1.
So it can be used as an expression

print accepts only one argument at a time

11

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
PHP
Key points to be remembered
To display the data as output in the screen,
3 ways can be used
1. echo or echo()
2. print or print()
3. print_r()
Display the information about the variable in
human readable form

PHP
Data types
2 types
1. Scalar data type
2. Compound data type
Scalar Compound Juggling
boolean Arrays Resources

integer Objects NULL

float

string

12

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
PHP
Data types [Scalar]
4 types {boolean, integer, float, string}
Scalar Description
boolean Simplest type – expresses a truth
values. Can be neither “True/False”
During casting, use “bool”
<? <?
//assign True to $a //compare
$a = True; if($name == “PSNA”){
?> echo “welcome !!!”;
}
?>

PHP
Data types [Scalar]
4 types {boolean, integer, float, string}
Scalar Description
integer Is the number set z = {… -2,-1,0,1,2,…}

specified in decimal (base 10),


hexadecimal (base 16), octal (base 8) or
binary (base 2) notation, optionally
preceded by a sign

13

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
PHP
Data types [Scalar]
4 types {boolean, integer, float, string}
Scalar Type Structure
integer decimal [1-9][0-9]* | 0

Hexadecimal 0[xX][0-9a-fA-F]+

octal 0[0-7]+

binary 0b[01]+

PHP
Data types [Scalar]
<? Integer overflow – PHP encounters a
$large_number
number= beyond
2147483647;
the bounds of integer type,
var_dump($large_number);
it is interpreted as “float” // int(2147483647)

$large_number = 2147483648;
var_dump($large_number); // float(2147483648)

$million = 1000000;
$large_number = 50000 * $million;
var_dump($large_number); // float(50000000000)
?>

14

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
PHP
Data types [Scalar]
4 types {boolean, integer, float, string}
Scalar Description
Floating point also known as "floats", "doubles", or
numbers "real numbers"
size of a float is platform-dependent,
although a maximum of ~1.8e308 with a
precision of roughly 14 decimal digits
<?
$a = 1.23;
$b = 1.2e3;
?>

PHP
Data types [Scalar]
4 types {boolean, integer, float, string}
Scalar Description
String series of characters - supports a 256-
character set – size of string is
maximum up to 2GB
4 ways:
Single quoted, double quoted, heredoc,
newdoc

Note: There is no character datatype

15

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
PHP

<?
echo 'this is a simple string';

// Output: "I ‘ll be back"


echo '"I\'ll be back"';

// Outputs: You deleted C:\*.*?


echo 'You deleted C:\*.*?';
?>

PHP
Data types [Scalar]
4 types {boolean, integer, float, string}
Scalar Description
String If double quoted – supports several
escape characters
\n – new line
\r – carriage
\t – horizontal tab
\\ - backslash
\$ - dollar sign
\\” – double quote

16

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
PHP
Data types [Scalar] - String
<!DOCTYPE html>
<html>
<body>
<?php
$x = "PSNA CET";
$y = 'Third CSE A’;
echo $x;
echo "<br>";
echo $y;
?>
</body>
</html>

PHP
Type conversion
Supports implicit & explicit type conversion

Implicit conversion (coercion)


Takes place between:
integer and double type
Boolean and scalar type
Numeric and string types

17

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
PHP
Type conversion
Supports implicit & explicit type conversion

Explicit conversion – 3 ways

Syntax Example
(datatype)$variable (int)$mark
Conversion_function($variable) Intval($mark)
Settype($variable,”datatype”) Settype($mark,”integer”)

PHP
Data types [Compound]
Arrays
Compound Description
Array It is an ordered map which associates
values to keys
3 ways it can be created
a) Indexed array (array with index)
b) Associative array (array with keys)
c) Multidimensional array (array has one or
more array)

18

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
PHP
Data types [Compound]: Indexed Array
Created by 2 forms

$total=array(“A”,”B”,”C”);

or
$total[0]=“A”;
$total[1]=“A”;
$total[2]=“A”;

Use count($array) for its size

PHP
Data types [Compound]: Associative Array
Uses named key - Created by 2 forms

$total=array(“A”=>”18”,”B”=>”17”,”C”=>”17”);

or
$total[“A”]=“18”;
$total[“B”]=“17”;
$total[“C”]=“17”;

Use count($array) for its size

19

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
PHP
Data types [Compound]: Indexed Array
Use “foreach” loop to process array

$total=array(“A”=>”18”,”B”=>”17”,”C”=>”17”);

foreach($total as $k=>$v){
echo $k.”=>”.$v.”<br>”;
}

PHP
Data types [Compound]: built in functions
Created by 2 forms

array() array_merge()
array_fill() array_push()
array_rand() array_shift()
array_slice() array_sum()
array_unique() count()
sort() array_reverse()
asort() arsort()

20

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
PHP
Data types [Compound]
Arrays
Compound Description
Array It is an ordered map which associates
values to keys
Can be created using “array()” or

<?php
$arr_name
$arr_name [key] =[0] = “Hi from”;
value;
$arr_name [1] = “Third CSE”;
$arr_name [2] = “A and B Section”;
echo $arr_name [0] . $arr_name [1]. $arr_name [2] ;
?>

PHP
Data types [Compound]
Objects
Compound Description
<?php
Object Instance for the class – use “new”
class sample{
function test(){
echo “total strength is: 60”;
}
}
$obj_new = new sample;
$obj_new->test();
?>

21

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
PHP
Data types [Juggling]
PHP doesn’t require the developer to
specify the data type for the variable at the
<?php
time of declaration
$a = 40 + “1”;
$b = “PSNACET”;
echo $a; echo $b;
$b += “A Section”;
echo $b;
$b .= “A Section”;
echo $b;
?>

PHP
Data types [Juggling – NULL]
Represents the variable with no value

<?
$a = NULL;
echo $b;
?>

22

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
PHP
Constants
Are variables except that once they are
defined they cannot be changed or
undefined

Characteristics
1. Case sensitive – global access
2. Expressed in uppercase letters
3. Can begin with underscore / letter
followed by any no. of underscore or
letter

PHP
Constants
Syntax

define(name, value, case-insensitive)

23

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
PHP
Constants
Example

<?php
define(“TOTAL", 60);
echo TOTAL;
?>

PHP
Operators
used to perform operations on variables
and values
Types
1. Arithmetic operators
2. Assignment operators
3. Comparison operators
4. Increment/Decrement operators
5. Logical operators
6. String operators
7. Array operators

24

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
PHP
Arithmetic Operators
to perform common arithmetical
operations, such as addition, subtraction,
multiplication
Oper. Name Example
+ Addition $a + $b
- Subtraction $a - $b
* Multiplication $a * $b
/ Division $a / $b
% Modulus $a % $b
** Exponentiation $a ** $b

PHP
Assignment Operators
to write a value to the variable

Oper. Same as Example


= x=y ?
+= x = x +y
-= x=x-y
*= X=x*y
/= x=x/y
%= x=x%y

25

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
PHP
Comparison Operators
to compare 2 values

Oper. Name Example


== Equal $x == $y
=== Identical $x === $y
!= Not equal $x != $y
<> Not equal $x <> $y
!== Not identical $x !== $y
> Greater than $x > $y

PHP
Comparison Operators
to compare 2 values

Oper. Name Example


< Less than $x < $y
>= Greater than $x >= $y
equal to
<= Less than $x <= $y
equal to

26

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
PHP
Increment / Decrement Operators
Used to increment / decrement variable
values
Oper. Name Description
++$a Pre increment Increment $a by one and
returns $a
$a++ Post increment Returns $a and
increment $a by one
--$a Pre-decrement ?
$a-- Post decrement ?

PHP
Logical Operators
Used to combine conditional statements
Oper. Example Description

and $a and $b Returns true if both are true


or $a or $b Returns true if either any one
is true
xor $a xor $b Returns true if either any one
is true but not both
&& $a && $b
|| $a || $b
! !$a

27

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
PHP
String Operators
to perform string handling operations

Oper. Name Example


. Concatenation $a.$b
.= Concatenation $a.=$b; appends
Assignment

PHP
Array Operators
to compare arrays

Oper. Name Example Description


+ Union $a+$b Union of $a and $b
== Equality $a==$b Returns true if $a and
$b has same key value
pairs
=== Identity Returns true if $a and
$b has same key value
pairs & both are same
data type

28

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
PHP
Array Operators
to compare arrays

Oper. Name Example Description


!= inequality $a!=$b Returns true if $a and
$b is not equal
<> Inequality $a<>$b Returns true if $a and
$b is not equal
!== Non-identity $a!==$b Returns true if $a and
$b is not identical

PHP
Control Structures
used to perform operations different
actions on different situation
Statement Types
1. If
2. If…else
3. If..elseif…else
4. switch
5. while
6. do..while
7. for & foreach

29

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
PHP
Control Structures
used to perform operations different
actions on different situation
Statement Description
if Executes block of code only if a
condition is true
if…else Executes some block of code if a
condition is true else another code
will be executed
if…elseif…else Specifies a new condition with in
“if” that too executes if the first
condition fails
switch Select one of many blocks

PHP
Control Structures
used to perform operations different
actions on different situation
Statement Description
While Loops thro’ a block of code as
long as the condition is true
Do…while Loops thro’ a block of code once &
then repeat the loop as long as the
condition is true
For Loops thro’ a block of code for
number of times
Foreach Loops thro’ a block of code for
each element in an array

30

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
PHP
Control Structures
“if” Statement
Used to execute some code if a
condition is true

if(condition){
//needed statements if true
}

PHP
Control Structures
“if…else” Statement
Used to execute some code if a
condition is true else another code will
be executed

if(condition){
//needed statements if true
}
else{
//needed statements
}

31

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
PHP
Control Structures
“if…elseif…else” Statement
Used to specify new condition if the
first condition is false
if(condition){
//needed statements if true
}
elseif(condition){
//needed statements
}
else{
//needed statements
}

PHP
Control Structures
“switch” Statement
Used to select one of many blocks

switch(a){
case label1: //execute if a=label1;
break;
:
:
default: …
}

32

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
PHP
Control Structures
“while” Statement
Used to execute the block as long as
the condition is true

while(condition){
//needed statements
}

PHP
Control Structures
“do…while” Statement
Used to execute the block once and
then repeat the loop as long as the
condition is true

do{
//needed statements
}
while(condition);

33

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
PHP
Control Structures
“for” Statement
Used to execute the block for the
specified no. of times

for(intialize;counter;increment / decrement){
//needed statements
}

PHP
Control Structures
“foreach” Statement
Used to execute only on arrays & used
to loop thro’ key/value pair

foreach($array as $value){
//needed statements
}

34

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
PHP
Problems
Implement a server side application using
PHP to:
1. Swap 2 positive integers
2. Compute arithmetic operations [switch]
3. Convert Fahrenheit to centigrade
4. Find maximum among 3 numbers
5. Calculate grade for the student
6. Reverse an integer [while]
7. Check whether the character is
alphabet

PHP
Functions
It is a block of statements to accomplish a
task, which will be executed when there is
a call

PHP has around 1000 built in functions

User can able to create own functions in a


program

35

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
PHP
Functions
Skeleton
function function_name([argument_list]){
//needed statements
}

A function name can start with letter / underscore


but not a number

PHP
Functions
Note
Function with default argument
Function with return values

Possible

36

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
PHP
Form Handling
This section explains how to process form
data
2 ways
Form Method Description
GET Used as: $_GET
POST Used as: $_POST

Both process the form data as array


that holds key / value pair

Key = form control names


Value = input data from the user

PHP
Arrays
Special variable which can hold more than
one value at a time

Use “array()” to create an array

3 types
1. Indexed arrays [array with numeric index]
2. Associative arrays [with named key]
3. Multidimensional arrays [has one / more
arrays]

37

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
PHP
Arrays
Indexed Arrays
Created by 2 ways

$a = array(“psna”,”cse”,”A section”);

$a[0] = “psna”;
$a[1] = ”cse”
$a[2] =”A section”;

PHP
Arrays
Associative Arrays
Uses key / value pair

$a = array(“cname”=>”psna”,”dept”=>”cse”,”section”=>”A”);

$a[“cname”] = “psna”;
$a[“dept”] = ”cse”
$a[“section”] =”A”;

38

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
PHP
Manipulating Arrays

Functions Description
count() returns the length of an array

array_shift() Remove the 1st element from an array

array_push() Add multiple variables to an array

array_merge() Join 2 arrays

array_intersect() Compare arrays and extract common


values

PHP
Manipulating Arrays

Functions Description
array_unique() Eliminate duplicate elements in an array

array_slice() Slice arrays


sort() Sort arrays
asort()
ksort()

39

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
PHP
Cookies
Used to identify the user

It is a piece of text that the server embeds


on users system

Whenever user initiates the request this


cookie will also sent along with the
request

PHP
Cookies
To create cookie

setCookie(name, value, expire, path, domain, secure, httponly)

Except name others are optional

40

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
<?php
$cookie_name = "user";
$cookie_value = “cse"; PHP
setcookie($cookie_name, $cookie_value, time() +
Cookies
(86400 * 30), "/"); // 86400 = 1 day
?>
<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>

PHP
Cookies
<?php
// set the expiration date to one hour ago
setcookie("user", “ ", time() - 3600);?>
<html>
<body>
<?php
<?php
echo "Cookie 'user' is deleted.";
?>

</body>
</html>

41

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
PHP
Cookies
To check whether cookie is enabled / not

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

PHP
Database connectivity
Using PHP, one can connect with databases

Supported DB:
1. MySQL
2. Oracle
3. SQL Server
4. Sybase
5. Powerbuilder Most suitable

42

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
PHP
Database connectivity: MySQL
Database system used on the web that
runs on a server
Ideal for both small and large applications
Very fast, reliable, and easy to use
Uses standard SQL & compiles on a
number of platforms
Free to download and use
Can be developed, distributed, and
supported by Oracle Corporation

PHP
Database connectivity: MySQL
PHP + MySQL = Cross platform support

i.e., can be designed in win and execute


on linux

43

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
PHP
What is MySQL?
It is a relational database management
system
open-source, free & ideal for both small
and large applications
very fast, reliable, scalable, and easy to
use, cross-platform
MySQL is compliant with the ANSI SQL
standard
MySQL was first released in 1995

PHP
Database connectivity: MySQL
Before accessing a data from database,
connection to the database must be
established

Can work with DB using


1. MySQL / MySQLi [i - improved]
2. PDO [PHP Data objecs]

Select any one

44

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
PHP
Database connectivity: MySQL
To connect with database server

mysql_connect($host,$uname,$pass);

$host = “DBServerName”
$uname = “DBServerUserName”;
$pass = “DBServerpassword”

mysqli_connect($host,$uname,$pass);

PHP
Database connectivity: MySQL
To create database

mysql_create_db(“psna");
Creates database named as “psna”

$sql="create database psnacse";


if($connection query($sql)===TRUE){
echo "Database created successfully with the new name";
} else {
echo "<br>Error creating database: " . $connection->error;
}

45

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
<?php
$host=“psna"; $uname=""; $pass="";
echo "PhP with Database<br>";
PHP
$connection=mysqli_connect($host,$uname,$pass);
echo "After connection<br>";
if(!$connection){
die("A connection to the server could not be
established<br>");
}
echo "Connected !!!<br>";
$sql="create database psnacse";
if($connection->query($sql)===TRUE){
echo "Database created successfully with new name";
} else {
echo "<br>Error creating database: " .
$connection->error;
}
?>

<?
$host=“psna";
$uname="";
PHP
$pass="";
$connection=mysqli_connect($host,$uname,$pass);
$db=“psnacse";
$new_relation="profile";
$error="The ".$db." could not be found";
$select_db=mysql_select_db($db) or die($error);

$query="create table ".$new_relation."(Name varchar(20)


Not Null,customerid varchar(20) Not Null Primary Key)";
$exequery=mysqli_query($query) or die("Query could not
be executed !!!");
echo "Query executed Successfully...";
?>
</body>
</html>

46

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
XML
Key points to be remembered
XML?
Difference between XML and HTML?
Design goals for XML?
Tools

XML
Key points to be remembered
XML stands for “eXtensible Markup Language”

XML is a markup language much like HTML,


which is designed to carry data, not to display
data

XML tags are not predefined. You must define


your own tags & is designed to be self-
descriptive

XML is a W3C Recommendation

47

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
XML
XML Vs. HTML
XML is not a replacement for HTML.

XML and HTML were designed with different


goals:
XML was designed to transport and store data,
with focus on what data is
HTML was designed to display data, with
focus on how data looks

i.e., HTML is about displaying information,


while XML is about carrying information

XML
Key points to be remembered
1. HTML is not a meta language. i.e., using HTML,
domain specific tag can not be used. One has to
use predefined tags.

2. HTML failed to be use with structure of the


document.
In general, all electronic documents will have 3
components
a) Structure
b) Content
c) format

48

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
XML
Key points to be remembered
2. HTML failed to be use with structure
Structure
It provides the framework so as to describe
how the document should be written

Format
Specifies the style of arrangement of the
document when it is visualized

Note: XML was created to structure, store, and


transport information.

XML
Key points to be remembered
3. HTML is not extensible
An extensible language helps to define custom
tags for application specific situations.

Example?

49

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
XML
Key points to be remembered
4. HTML is very display-centric and not structure
oriented
Using HTML
one can display the form data or elements.
Can make the text as bold, italic and image
alignment
i.e., it represents the data by layout without
meaning

No semantic Structure

XML
Key points to be remembered
4. HTML is very display-centric and not structure
oriented
Representing data by meaning provides many
advantageous when efficient searches are to
conducted by search engines

Example?
Search engine with HTML Webpage’s offers
Herculean task – “Unnecessary links”
Using XML, it provides intelligent searches
where only relevant information will be
obtained

50

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
XML
Design Goals
XML documents should be
easy to create
Formal and concise
Human legible & clear
Easily usable across the internet

XML
Key points to be remembered
To work with XML documents, all should be
stored with “.xml” extension

Tools?
1. Editor.
Example: XML Notepad, XML Spy, Text Pad
etc.,
2. Browser.

51

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
XML
Key points to be remembered
XML Documents Form a Tree Structure
XML documents must contain a single root
element. This element is "the parent" of all
other elements.

The elements in an XML document form a


“document tree”. The tree starts at the root and
branches to the lowest level of the tree.

All elements can have sub elements (child


elements):

XML
Key points to be remembered
XML Documents Form a Tree Structure

Example

<root>
<child>
<subchild>.....</subchild>
</child>
</root>

Single root tag

52

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
XML
Key points to be remembered
XML Document begins with

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

XML
Key points to be remembered
XML Documents Well formed
Depicts the structure of the document

“Well formed XML document” is one that


follows all of the notational and structural rules
for XML

To find the well formness, XML uses parser,


which checks the structure of the document-
else it produces the error

53

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
XML
Key points to be remembered
No unclosed tags
In HTML, one can use starting tag & forget to
use closing tag. During its execution, browser
recognizes & displays something.

But XML is very strict about these mistakes.


Every tag must have a corresponding closing
tag.

XML
Key points to be remembered
No unclosed tags
In HTML, some elements do not have to have a
closing tag:
<p>This is a paragraph
<p>This is another paragraph

In XML, it is illegal to omit the closing tag. All


elements must have a closing tag:
<para>This is a paragraph</para>
<para>This is another paragraph</para>

54

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
XML
Key points to be remembered
No overlapping of tags
A tag that opens inside another tag must close
before the first one.

Example.
<root>
<pizza> lets have a pizza
<burger> or should we have a burger
</pizza></burger>
</root>

XML
Key points to be remembered
Enclose the attribute value using quotes
In HTML, some element’s attributes may
specified without quotes

<IMG src=cse.jpg>

In XML, it is illegal to omit the quotes – else it


says illegal literal error

<IMG src=“cse.jpg”></IMG>

55

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
XML
Key points to be remembered
Naming of tags
In XML, all elements must have opening “<”
and closing “>” tags

It can not begin with digits, hyphens

Not allowed elements

<3test>Serial Test 3</3test>


Begins with digits

XML
Key points to be remembered
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 incorrect</message>
<message>This is correct</message>

56

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
XML
Key points to be remembered
XML document considered to have 2 structures.
1. Tree Structure or Logical Structure
2. Physical Structure

XML
Key points to be remembered
Tree structure
XML document will be displayed as a
hierarchical data, which resembles like a “Tree
Structure”

Example?

57

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
XML
Key points to be remembered
Tree structure

bme
students
cse
PSNA

cse
staffs
bme

XML
Key points to be remembered
Physical structure
XML document will be made as a number of
physical files referred as “Entity”.

It describes the actual bits where the entities


are stored

58

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
XML
Create XML Document
Create a document with domain specific tags and
store it as “.xml” extension

Tag?
It is a piece of text that must be enclosed
between angle brackets

XML must have both opening and closing tags

XML
Create XML Document

<?xml version=“1.0”?>
<college>
<psna>
<student>….</student>
<psna>
</college>

Valid

59

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
XML
Create XML Document

<?xml version=“1.0”?>
<college>
<psna>
<student>
</psna>
</college>

In-Valid XML
Cos’ there is no closing of student tag

XML
Create XML Document
Rules to use Tag
<openingtag> - says starting element

</closingtag> - says end element

<test/> - says both opening & closing tag in a


single line

<Third CSE> - Bad starting tag coz’ no space


are allowed

<56> - bad start tag coz’ tag should not begin


with digits, hypens

60

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
XML
Create XML Document
Attributes
Properties to a particular tag

It describes how the tag should be used

Example?

XML
Create XML Document
XML Element Vs. XML Attributes

Example 1 Example 2
<person>
<person gender="female">
<gender>female</gender>
<firstname>Anna</firstname>
<firstname>Anna</firstname>
<lastname>Smith</lastname>
<lastname>Smith</lastname>
</person>
</person>

In the first example gender is an attribute. In the last, gender is an element.


Both examples provide the same information

61

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
XML
Create XML Document
Comments
Used for later reference

<!-- statements -->

XML
Create XML Document
Summary
XML elements must follow these naming rules:
Names can contain letters, numbers, and
other characters

Names cannot start with a number or


punctuation character

Names cannot start with the letters xml (or


XML, or Xml, etc)

Names cannot contain spaces

62

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
XML
Well formed XML Document
Depicts the structure of the document

“Well formed XML document” is one that follows


all of the notational and structural rules for XML

XML
Well formed XML Document
Syntax rules for XML
XML documents must have a single root
element

XML elements must have a closing tag

XML tags are case sensitive

XML elements must be properly nested

XML attribute values must be quoted

63

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
XML
Well formed XML Document
To find the well formness, XML uses parser,
which checks the structure of the document- else
it produces the error

XML Parser makes use of DTD / Schema for


validating the XML document structure

XML
Well formed XML Document: DTD
Document Type Definition

DTD is the rules that must be followed in the


documents

It is the foundation of valid XML documents for


proving its structure

64

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
XML
Well formed XML Document: DTD
DTD (2 kinds)
1. External DTD

2. Internal DTD
Rules will be specified or embedded inside the same
XML document

XML
Well formed XML Document: DTD
External DTD
A separate file is created with “.dtd” extension

Invoke this external file into the XML document


using the following syntax

<!DOCTYPE root-element SYSTEM “dtd-url”>

65

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
XML
Examples
1. Create a XML document to remind about
appointment to a friend

2. Create a XML document for business letter

XML
Solution 1: Create a XML document to remind about
appointment to a friend
Steps
1. create XML document
<?xml version="1.0" encoding="ISO-8859-1"?>
2. Associate DTD file with document
<!DOCTYPE note SYSTEM "Note.dtd">
<note>
<to>Friend Name</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

66

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
XML
Solution 1: Create a XML document to remind about
appointment to a friend

<!ELEMENT note (to,from,heading,body)>


<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>

Internal DTD ?

XML
Solution 2: Create a XML document for Business
Letter

<!ELEMENT letter (date, insideaddress, salutation,


body, closing, signature)>
<!ELEMENT date (#PCDATA)>
<!ELEMENT date align (left | right) “left”>
<!ELEMENT insideaddress (#PCDATA | br*)>
<!ELEMENT br EMPTY)>
<!ELEMENT salutation (#PCDATA)>
<!ELEMENT body (P+)>
<!ELEMENT p (#PCDATA)>
<!ELEMENT p align (left | justify | right) “left”>
<!ELEMENT closing (#PCDATA)>
<!ELEMENT signature (#PCDATA)>

67

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
XML
Tags Data Set (data type supported)
PCDATA - parsed character data
CDATA - character data
Any - can take any type of content

XML
Tags Occurrence

<!ELEMENT element-name (child-name)>

Example

<!DOCTYPE note [
<!ELEMENT note (message)>
]>
<note>
<message>…</message>
</note>

68

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
XML
Tags Occurrence

<!ELEMENT element-name (child-name*)>

Example

<!DOCTYPE note [
<!ELEMENT note (message*)>
]>
<note>
<message>…</message>
<message>…</message>
</note>

XML
Tags Occurrence

<!ELEMENT element-name (child-name+)>

Example

<!DOCTYPE note [
<!ELEMENT note (message+)>
]>
<note>
<message>…</message>
<message>…</message>
</note>

69

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
XML
Tags Occurrence

<!ELEMENT element-name (child-name?)>

Example

<!DOCTYPE note [
<!ELEMENT note (message?)>
]>
<note>
<message>…</message>
</note>

XML
XPoint
XML Pointers

Used to point the position of XML element in the


document tree

Example: Business letter


Child(1,body) => first child of body element

Child(3,p)…child(5,p) => spans the multiple


elements

70

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
XML
Problems
1. Consider a hospital management system. Write a
DTD program to consolidate and show the bill to
be paid by the inpatients (Assume your own data)

2. Create a DTD for a catalog of 4 stroke bikes,


where each motor bike has the following child
elements as make, model, year, color, engine,
chasis number and accessories. The engine
element has the child elements as engine no., no
of cylinders, fuel type. The accessories element
has the attributes like disc brake, auto start and
radio, each of which is required and has the
possible values yes and no.

XML
Merits: DTD
1. Used to define the structural elements of XML

2. Relatively simple and compact

3. Can be defined inline i.e., embedded inside the


document

71

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
XML
Demerits: DTD
1. Supports with basic types – does not support
complex types

2. DTD is not a XML document so it is not


supported by various frameworks

XML
XML Schema
Similar to DTD – also said as “XSD”

Created by Microsoft in order overcome the


limitations of DTD

“XML Schema” is an XML based alternative to DTD


& describes the structure of XML document

XML Schemas are themselves XML documents

In DTD, rules for an element & its attribute has to


be specified more detail

72

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
XML
XML Schema
Purpose
The purpose of an XML Schema is to define the
legal building blocks of an XML document, just
like a DTD.

XML
XML Schema
Purpose i.e., It defines
Elements & attribute that can appear in a
document
The number of child elements & which
elements are child elements
The order of child elements
Whether an element is empty or can include
text
Data types for elements and attributes
default and fixed values for elements and
attributes

73

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
XML
XML Schema
XML Schemas provides an Object Oriented
approach to defining the format of an XML
document.

To do that Schemas provide a set of basic types.


These types are like PCDATA and CDATA of
DTDs.

They include most basic programming types


such as integer, byte, string and floating point
numbers

XML
XML Schema

Functions Description
xs:element To represent the element of XML

xs:complexType To represent the type of element

xs:sequence Sequence of elements for an element

74

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
XML
Remind about appointment

<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="note">
<xs:complexType>
<xs:sequence>
<xs:element name="to" type="xs:string"/>
<xs:element name="from" type="xs:string"/>
<xs:element name="heading" type="xs:string"/>
<xs:element name="body" type="xs:string"/>
</xs:sequence>
</xs:complexType>
Schema
</xs:element>
</xs:schema>

XML
XML Schema is more powerful than DTD
They are:
Written in XML
Support data types (int, byte, string, float etc.,)
Support namespaces

Convert data from one to another


Validate the correctness of data
Defines the restrictions of data

75

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
XML
XML Schema: Problems
1. Write a XML Program to display the Shipping
details of any person who purchased 2 Items

2. Implement a sample XML document


To display the college course list?
To display computer science books based on
area of specialization?

XML
Generate XML Document with PHP
Used to generate response from the server as
XML

<?php
header("Content-type: text/xml");
echo "<?xml version='1.0' encoding='UTF-8'?>";
echo "<note>";
echo "<from>Third CSE</from>";
echo "<to>HOD CSE</to>";
echo "<message>Remember me this weekend";
echo "</message></note>";
?>

76

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
XML
Generate XML Document with JSP
Used to generate response from the server as
XML

<%
response.ContentType="text/xml“;
out.println("<?xml version='1.0' encoding='UTF-8'?>");
out.println("<note>");
out.println("<from>Third CSE</from>");
out.println("<to>HOD CSE</to>");
out.println("<message>Remember me this");
out.println(" weekend</message></note>");
%>

XML
Key points to be remembered
A response from database also represented as
XML

77

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
XML
DTD XSD
stands for Document XSD stands for XML Schema
Type Definition Definition
derived written in XML
from SGML syntax
doesn't support supports datatypes for
datatypes elements and attributes
doesn't support supports namespace
namespace
doesn't define order for defines order for child elements
child elements
not extensible extensible

XML
Merits: Schema
1. It is a XML document that can be used as more
specific and provides support for more data
types

2. Uses namespaces to avoid naming conflicts

Demerits: Schema
1. It is complex to learn and design
2. Maintenance is hectic – larger / complex
operations may slow down the processing of
XML document

78

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
XML DOM
XML Parsers
It is a software library or package that provides
interfaces for client applications to work with an
XML document.

It is designed to read the XML and create a way for


programs to use XML.

Use: XML parser validates the document and check


that the document is well formatted

XML DOM
XML Parsers

Parsers Client
XML Doc

79

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
XML DOM
XML Parsers
Types
1. DOM Parser
2. SAX Parser

XML DOM
DOM Parsers
contains all the information of an XML document

composed like a tree structure

implements a DOM API. This API is very simple to


use

creates an internal structure in memory which is a


DOM document object and the client applications
get information of the original XML document by
invoking methods on this document object

80

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
XML DOM
DOM Parsers
Advantages
1. Supports both read and write operations and
the API is very simple to use.

2. Preferred when random access to widely


separated parts of a document is required.

XML DOM
DOM Parsers
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.

81

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
XML DOM
SAX Parsers
Simple API for XML

does not create any internal structure.

It is an event based parser, it works like an event


handler in Java.

XML DOM
SAX Parsers
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.

82

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
XML DOM
SAX Parsers Vs. DOM
In SAX, events are triggered when the XML is being
parsed.

When the parser is parsing the XML, and


encounters a tag starting (e.g. <something>), then
it triggers the “tagStarted” event (actual name of
event might differ). Similarly when the end of the
tag is met while parsing (</something>), it triggers
“tagEnded”.

Using a SAX parser implies you need to handle


these events and make sense of the data returned
with each event.

XML DOM
SAX Parsers Vs. DOM
In DOM, there are no events triggered while
parsing. The entire XML is parsed and a DOM tree
(of the nodes in the XML) is generated and
returned.

Once parsed, the user can navigate the tree to


access the various data previously embedded in
the various nodes in the XML.

83

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
XML DOM
Key points to be remembered
XML Document Object Model

It defines way in which the XML elements can be


accessed and manipulated

Similar to HTML DOM

XML DOM
Key points to be remembered
Document Object Model (DOM)
It 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.

3 parts
1. Core DOM
2. XML DOM
3. HTML DOM

84

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
XML DOM
Key points to be remembered
It defines way in which the XML elements can be
accessed and manipulated

To access / manipulate, it defines the objects,


properties and methods of all XML elements

The XML DOM is:


A standard object model for XML
A standard programming interface for XML
Platform- and language-independent
A W3C standard

XML DOM
Key points to be remembered
What you can do?
makes a tree-structure view for an XML
document
access / manipulate all elements through the
DOM tree

Steps:
1. Load the XML document
2. Access / manipulate the element using hierarchy

85

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
XML DOM
Key points to be remembered
To get the value of XML Element

txt = xmlDoc.getElementsByTagName(“element")[0].
childNodes[0].nodeValue;

XML DOM
Key points to be remembered
To Load the XML file
Before interpreting XML document one has to
load the XML document, based on the type of
Browser

Browser Use
Internet Explorer (IE5, IE6) ActiveXObject
IE7+, Firefox, Chrome, Opera, XMLHttpRequest
Safari

86

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
XML DOM
Example

sample.xml

<?xml version="1.0" encoding="ISO-8859-1"?>


<note>
<from>Third CSE</from>
<to>HOD CSE</to>
<heading>Work shop</heading>
<body>Meeting at 9.00 AM</body>
</note>

<html>
<body> XML DOM
<h1> Example </h1>
Example
<div>
<b>To:</b> <span id="to"></span><br>
<b>From:</b> <span id="from"></span><br>
<b>Message:</b> <span id="message"></span>
</div>
<script>
if (window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}

87

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
XML DOM
xmlhttp.open("GET",“sample.xml",false);
Example
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;

document.getElementById("to").innerHTML=
xmlDoc.getElementsByTagName("to")[0].childNodes[0].nodeValue;

document.getElementById("from").innerHTML=
xmlDoc.getElementsByTagName("from")[0].childNodes[0].nodeValue;

document.getElementById("message").innerHTML=
xmlDoc.getElementsByTagName("body")[0].childNodes[0].nodeValue;

</script>
</body>
</html>

DOM Vs SAX
DOM SAX
It is a tree based parsing It is a event based parsing
method method
Here, entire XML is stored in Parsing is done by generating
the memory before processing sequence of events
– so it may required more
memory
Useful for smaller Useful for parsing larger
applications XML documents

88

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
XSLT
Key points to be remembered
Stands for “eXtensible Style sheet Language
Transformation”

It is used to transform the XML document to other


formats like XHTML

XSLT
Precursor

XSL EXtensible Style sheet Language

Gives appearance to XML

1. XML with CSS


XSLT 2. XML with XSL

89

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
XSLT
Problem
Design a XML based web application using CSS
that represent 6th semester books to be used for
students that should display title, author name,
publication, price in different fonts and color

XSLT
Precursor
XSL has 3 parts
1. XSLT (to transform XML into other)
2. Xpath (to navigate XML)
3. XSL-FO (to format XML)

90

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
XSLT
XSL (Summary)
eXtensible
Use Stylesheet Language Description
<xsl:stylesheet> indicates that this document is
a styletosheet
Used to add appearance the web page
<xsl:template match=“/”> indicate that this is a template
thatabove
Works with IE 5.0 and corresponds to the root (/)
of the XML source document
<xsl:for-each> locates elements in the XML
document and repeats a
template for each one
<xsl:value-of> selects a child in the hierarchy
and inserts the content of that
child into the template

XSLT
Key points to be rememebered
Convert from XML to HTML
Create
1. XML document (.xml)
2. XSL Document (.xsl)
3. HTML File (.html) [conversion code
appears]

Conversion is made at client or server side

Example ?

91

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Sample.xml XSLT
<?xml version="1.0" encoding="ISO-8859-1"?>
<psna>
<dept category=“thirdcse”>
<Name>Third CSE</Name>
<Age>18</Age>
<Email>[email protected]</Email>
<Address>CSE 3rd floor</Address>
</dept>
<dept category=“secondcse”>
<Name>second CSE</Name>
<Age>17</Age>
<Email>[email protected]</Email>
<Address>CSE 2nd floor</Address>
</dept>
</psna>

Sample.xsl XSLT
<?xml version='1.0'?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/TR/WD-xsl">
<xsl:template match="/">
<html> <body>
<table border="2" bgcolor="yellow">
<tr> <th>Name</th> <th>Email ID</th> </tr>
<xsl:for-each select=“psna/dept">
<tr>
<td><xsl:value-of select=“Name"/></td>
<td><xsl:value-of select=“Email"/></td>
</tr>
</xsl:for-each>
</table>
</body></html>
</xsl:template>
</xsl:stylesheet

92

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Sample.html XSLT
<html><body>
<script language="javascript">
// Load XML
var xml = new ActiveXObject("Microsoft.XMLDOM")
xml.async = false
xml.load(“sample.xml")

// Load the XSL


var xsl = new ActiveXObject("Microsoft.XMLDOM")
xsl.async = false
xsl.load("sample.xsl")

// Transform
document.write(xml.transformNode(xsl))
</script></body></html>

Sample.html XSLT
<%
'Load the XML
set xml = Server.CreateObject("Microsoft.XMLDOM")
xml.async = false
xml.load(Server.MapPath(“sample.xml"))

'Load the XSL


set xsl = Server.CreateObject("Microsoft.XMLDOM")
xsl.async = false
xsl.load(Server.MapPath(“sample.xsl"))

Response.Write(xml.transformNode(xsl))
%>

93

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
XSLT
XSL Sort
To sort the contents in XML file, use “order-by”
attribute in <xsl:for-each select=“psna/dept”>
element

This attribute takes “+” or “-” sign to define


ascending / descending order of elements

XSLT
XSL Filter
While retrieving contents from XML file, one can
select the appropriate elements using “XSL Filter”

For this, simply add filter to the select attribute in


your for-each element

<xsl:for-each select=“psna/dept[Name=‘Third
CSE’]”>

94

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
XSLT
XSL filter
Supports 4 filter operators
1. =
2. =!
3. &LT
4. &GT

XSLT
XSL Conditional
<xsl:If>
<xsl:choose> & <xsl:when>

95

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
XML Namespace
Key points to be remembered
XML Namespaces provide a method to avoid
element name conflicts.

It is declared using reserved attributes whose


name must begin with “xmlns”

i.e., The namespace is defined by the xmlns


attribute in the start tag of an element.

The namespace declaration has the following


syntax xmlns:prefix="URI".

XML Namespace
Key points to be remembered
XML allows document authors to create custom
elements.

This extensibility can result in naming collisions


(i.e. different elements that have the same name)
among elements in an XML document.

An XML namespace is a collection of element and


attribute names. Each namespace has a unique
name that provides a means for document authors
to unambiguously refer to elements with the same
name (i.e. prevent collisions).

96

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
XML Namespace
Key points to be remembered
For example, consider 2 elements
<subject>Geometry</subject> and
<subject>Cardiology</subject>

use element subject to markup data. In the first


case the subject is something one studies in
school, whereas in the second case the subject is
in the field of medicine.

XML Namespace
Key points to be remembered
Namespaces can differentiate these two subject
elements.

For example,
<school:subject>Math</school:subject>
and
<medical:subject>Thrombosis</medical:subject>

97

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
XML Namespace
Key points to be remembered
Both school and medical are namespace prefixes.
A document author prepends a namespace prefix
to an element or attribute name to specify the
namespace for that element or attribute.

Each namespace prefix has a corresponding


uniform resource identifier (URI) that uniquely
identifies the namespace.

A URI is simply a series of characters for


differentiating names.

98

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]

You might also like