Unit 4
Unit 4
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
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”
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
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
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
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
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,…}
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
15
Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
PHP
<?
echo 'this is a simple string';
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
17
Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
PHP
Type conversion
Supports implicit & explicit type conversion
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”;
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”;
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
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
25
Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
PHP
Comparison Operators
to compare 2 values
PHP
Comparison Operators
to compare 2 values
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
27
Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
PHP
String Operators
to perform string handling operations
PHP
Array Operators
to compare arrays
28
Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
PHP
Array Operators
to compare arrays
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
35
Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
PHP
Functions
Skeleton
function function_name([argument_list]){
//needed statements
}
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
PHP
Arrays
Special variable which can hold more than
one value at a time
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
PHP
Manipulating Arrays
Functions Description
array_unique() Eliminate duplicate elements in an array
39
Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
PHP
Cookies
Used to identify the user
PHP
Cookies
To create cookie
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
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
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”
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);
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”
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
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.
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
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.
XML
Key points to be remembered
XML Documents Form a Tree Structure
Example
<root>
<child>
<subchild>.....</subchild>
</child>
</root>
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
Key points to be remembered
XML Documents Well formed
Depicts the structure of the document
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.
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
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>
<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
XML
Key points to be remembered
XML tags are case sensitive
The tag <Letter> is different from the tag
<letter>.
<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”.
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
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
60
Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
XML
Create XML Document
Attributes
Properties to a particular tag
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>
61
Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
XML
Create XML Document
Comments
Used for later reference
XML
Create XML Document
Summary
XML elements must follow these naming rules:
Names can contain letters, numbers, and
other characters
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
XML
Well formed XML Document
Syntax rules for XML
XML documents must have a single root
element
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
Well formed XML Document: DTD
Document Type Definition
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
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
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
Internal DTD ?
XML
Solution 2: Create a XML document for Business
Letter
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
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
Example
<!DOCTYPE note [
<!ELEMENT note (message*)>
]>
<note>
<message>…</message>
<message>…</message>
</note>
XML
Tags Occurrence
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
Example
<!DOCTYPE note [
<!ELEMENT note (message?)>
]>
<note>
<message>…</message>
</note>
XML
XPoint
XML Pointers
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)
XML
Merits: DTD
1. Used to define the structural elements of XML
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
XML
XML Schema
Similar to DTD – also said as “XSD”
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.
XML
XML Schema
Functions Description
xs:element To represent the element of XML
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
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
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
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.
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
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.
XML DOM
DOM Parsers
Disadvantages
1. It is memory inefficient. (consumes more
memory because the whole XML document
needs to loaded into memory).
81
Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
XML DOM
SAX Parsers
Simple API for XML
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.
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.
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
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
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
<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”
XSLT
Precursor
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]
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")
// 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"))
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
XSLT
XSL Filter
While retrieving contents from XML file, one can
select the appropriate elements using “XSL Filter”
<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. <
4. >
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.
XML Namespace
Key points to be remembered
XML allows document authors to create custom
elements.
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>
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.
98
Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]