Csdlo5012 Unit V Ip Notes
Csdlo5012 Unit V Ip Notes
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
UNIT-IV
PHP and XML
An introduction to PHP: PHP- Using PHP- Variables- Program control- Built-in functions- Form
Validation- Regular Expressions - File handling – Cookies - Connecting to Database. XML: Basic
XML- Document Type Definition- XML Schema DOM and Presenting XML, XML Parsers and
Validation, XSL and XSLT Transformation, News Feed (RSS and ATOM).
An introduction to PHP
PHP is a server scripting language, and a powerful tool for making dynamic and interactive
Web pages.
What is PHP?
PHP is an acronym for "PHP: Hypertext Preprocessor"
PHP files can contain text, HTML, CSS, JavaScript, and PHP code
PHP code are executed on the server, and the result is returned to the browser as plain
HTML
PHP files have extension ".php"
Why PHP?
[Department of CSE] 1
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
PHP 5 Syntax
A PHP script is executed on the server, and the plain HTML result is sent back to the
browser.
Comments in PHP
A comment in PHP code is a line that is not read/executed as part of the program. Its only
purpose is to be read by someone who is looking at the code.
<!DOCTYPE html>
<html><body>
<?php
// This is a single-line comment
# This is also a single-line comment
/*
This is a multiple-lines comment block
that spans over multiple
lines
*/?>
</body></html>
[Department of CSE] 2
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
PHP Variables
A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume).
Rules for PHP variables:
A variable starts with the $ sign, followed by the name of the variable
A variable name must start with a letter or the underscore character
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and
_)
Variable names are case-sensitive ($age and $AGE are two different variables)
In PHP, a variable starts with the $ sign, followed by the name of the variable:
Eg1:
<!DOCTYPE html>
<html><body>
<?php
$txt = "Hello world!";
[Department of CSE] 3
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
$x = 5;
$y = 10.5;
echo $txt;
echo "<br>";
echo $x;
echo "<br>";
echo $y;
?>
</body></html>
Eg2:
<!DOCTYPE html>
<html><body>
<?php
$txt = "W3Schools.com";
echo "I love $txt!";
?>
</body></html>
Eg:3
<!DOCTYPE html>
<html><body>
<?php
$x = 5;
$y = 4;
echo $x + $y;
?>
</body></html>
local
global
static
Local Scope
A variable declared inside a function has a local scope and can only be accessed inside a
function:
Eg:
[Department of CSE] 4
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
<body>
<?php
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
// using x outside the function will generate an error
echo "<p>Variable x outside function is: $x</p>";
?>
O/P:
Variable x inside function is:5
Variable x inside function is:0
Global Scope
A variable declared outside a function has a global scope and can only be accessed outside
a function:
Eg:
<html><body>
<?php
$x = 5; // global scope
function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
echo "<p>Variable x outside function is: $x</p>";
?>
</body></html>
O/P:
Variable x inside function is:0
Variable x inside function is:5
[Department of CSE] 5
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
$y = $x + $y;
}
myTest();
echo $y; // outputs 15
?>
O/P: 15
[Department of CSE] 6
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
String
Integer
Float (floating point numbers - also called double)
Boolean
Array
Object
NULL
Resource
A string is a sequence of characters, like "Hello world!".
PHP String:
Eg:
<?php
$x = "Hello world!";
$y = 'Hello world!';
echo $x;
echo "<br>";
echo $y;
?>
PHP Integer
An integer is a whole number (without decimals). It is a number between -2,147,483,648
and +2,147,483,647.
Rules for integers:
Eg:
<?php
$x = 5985;
var_dump($x);
?>
PHP Float
A float (floating point number) is a number with a decimal point or a number in
exponential form.
[Department of CSE] 7
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
Eg:
<?php
$x = 10.365;
var_dump($x);
?>
PHP Boolean
A Boolean represents two possible states: TRUE or FALSE.
$x = true;
$y = false;
PHP Array
An array stores multiple values in one single variable.
<?php
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
?>
PHP Object
An object is a data type which stores data and information on how to process that data.In
PHP, an object must be explicitly declared.
Eg:
<?php
class Car {
function Car() {
$this->model = "VW";
}
}
// create an object
$a = new Car();
// show object properties
echo $a->model; //VW
?>
Program control
a)PHP Control Structures
Any PHP script is built out of a series of statements. A statement can be an assignment,
a function call, a loop, a conditional statement of even a statement that does nothing (an empty
statement). Statements usually end with a semicolon. In addition, statements can be grouped into
a statement-group by encapsulating a group of statements with curly braces. A statement-group is
a statement by itself as well.
[Department of CSE] 8
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
1). If Statement
2). Else Statement
3). Elseif Statement
4). Switch Statement
Eg:
<?php
$t = date("H");
if ($t < "20") {
echo "Have a good day!";
}
?>
Syntax
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
EG:
<?php
$t = date("H");
if ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>
[Department of CSE] 9
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
Syntax
if (condition) {
code to be executed if condition is true;
} elseif (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
Eg:
<?php
$t = date("H");
if ($t < "10") {
echo "Have a good morning!";
} elseif ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>
Eg:
<?php
$favcolor = "red";
switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
[Department of CSE] 10
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
?>
b)PHP Loops Control
Often when you write code, you want the same block of code to run over and over again
in a row. Instead of adding several almost equal code-lines in a script, we can use loops to
perform a task like this.
In PHP, we have the following looping statements:
while - loops through a block of code as long as the specified condition is true
do...while - loops through a block of code once, and then repeats the loop as long as the
specified condition is true
for - loops through a block of code a specified number of times
foreach - loops through a block of code for each element in an array
Eg:
<?php
$x = 1;
while($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
?>
The PHP do...while Loop
The do...while loop will always execute the block of code once, it will then check the
condition, and repeat the loop while the specified condition is true.
Syntax,
do {
code to be executed;
} while (condition is true);
[Department of CSE] 11
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
Eg:
<?php
$x = 1;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
Eg:
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
PHP Array
What is an Array?
An array is a special variable, which can hold more than one value at a time.
Eg:
<!DOCTYPE html>
<html>
<body>
[Department of CSE] 12
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
</body>
</html>
Output:Volvo,BMW,Toyota
Eg:
<?php
function familyName($fname) {
echo "$fname Refsnes.<br>";
}
familyName("Jani");
familyName("Hege");
familyName("Stale");
familyName("Kai Jim");
familyName("Borge");
?>
[Department of CSE] 13
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
PHP functions:
Array functions
Calendar functions
Date functions
Directory functions
Error functions
Filesystem functions
a)Array Function
Some of the PHP Array Functions are,
PHP Count
The count() function is used to return the length (the number of elements) of an array:
Eg:
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo count($cars);
?>
Output: 3
Eg:
<?php
$cars = array("Volvo", "BMW", "Toyota");
sort($cars);
?>
Output:BMW,Toyoto,Volvo
[Department of CSE] 14
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
Eg:
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
asort($age);
?>
Output:
Peter 35
Ben 37
Joe 43
Eg:
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
arsort($age);
?>
output:
Joe 43
Ben 37
Peter 35
Function Description
cal_days_in_month() Returns the number of days in a month for a specified year and
calendar
easter_date() Returns the Unix timestamp for midnight on Easter of a specified year
easter_days() Returns the number of days after March 21, that the Easter Day is in a
specified year
[Department of CSE] 16
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
<?php
$d=cal_to_jd(CAL_GREGORIAN,6,20,2007);
echo $d;
?>
</body></html>
OUTPUT: 2454272
Function Description
date_add() Adds days, months, years, hours, minutes, and seconds to a date
Eg1: checkdate()
<?php
var_dump(checkdate(12,31,-400));
echo "<br>";
var_dump(checkdate(2,29,2003));
echo "<br>";
var_dump(checkdate(2,29,2004));
?>
O/P: bool(false)
bool(false)
bool(true)
Eg2: date_create()
<?php
$date=date_create("2013-03-15");
date_add($date,date_interval_create_from_date_string("40 days"));
echo date_format($date,"Y-m-d");
?>
O/P: 2013-04-24
[Department of CSE] 17
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
Eg: <?php
$date=date_create_from_format("j-M-Y","15-Mar-2013");
echo date_format($date,"Y/m/d");
?>
O/P: 2013/03/15
Validation means check the input submitted by the user. There are two types of validation are
available in PHP. They are as follows −
Validation Rules
Field
Eg:
<html><body>
<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
[Department of CSE] 18
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
$email = test_input($_POST["email"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
[Department of CSE] 19
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
// create a string
$string = 'abcdefghijklmnopqrstuvwxyz0123456789';
// try to match the beginning of the string
if(preg_match("/^abc/", $string))
{
// if it matches we echo this line
echo 'The string begins with abc';
}
else
{
// if no match is found echo this line
echo 'No match found';
}
?>
c)Case Insensitive
If you used the above code to find the pattern ABC like this,if(preg_match("/^ABC/",
$string)) the script would have returned the message:No match found
EG: <?php
// create a string
$string = 'abcdefghijklmnopqrstuvwxyz0123456789';
// try to match our pattern
if(preg_match("/^ABC/i", $string))// specify i
{
// echo this is it matches
echo 'The string begins with abc';
}
else
{
// if not match is found echo this line
echo 'No match found';
}
?>
d)Find a pattern at the end of the string
This is done in much the same way as with finding a a pattern at the beginning of a
string. A common mistake made by many is to use the $ character to match the end of a string.
This is incorrect and \z should be used. Consider this. preg_match("/^foo$/", "foo\n")
Eg:
<?php
// create a string
$string = 'abcdefghijklmnopqrstuvwxyz0123456789';
// try to match our pattern at the end of the string
if(preg_match("/89\z/i", $string))
{
// if our pattern matches we echo this
echo 'The string ends with 89';
[Department of CSE] 20
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
}
else
{
// if no match is found we echo this line
echo 'No match found';
}
?>
e)Meta Characters
During our first look at regex we did some simple pattern matching. We also introduced
the caret(^) and the dollar($). These characters have special meaning. As we saw, the caret(^)
matched the beginning of a string and the dollar matched the end of a string. These characters,
along with others are called Meta characters. Here is a list of the Meta characters used for regex:
. (Full stop)
^ (Carat)
* (Asterix)
+ (Plus)
? (Question Mark)
{ (Opening curly brace)
[ (Opening brace)
] (Closing brace)
\ (Backslash)
| (Pipe)
( (Opening parens)
) (Closing parens)
} (Closing curly brace)
EG1:backslash
<?php
// create a string
$string = '1+1=2';
// try to match our pattern
if(preg_match("/^1\+1/i", $string))
{
// if the pattern matches we echo this
echo 'The string begins with 1+1';
}
else
{
// if no match is found we echo this line
echo 'No match found';
}
?>
OUTPUTP: The string begins with 1+1
[Department of CSE] 21
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
[Department of CSE] 22
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
OUTPUT:
The code above will return this:
six
at
noon
taxes
4
EG:Find for a match with pattern php in the string
<?php
// create a string
$string = 'pp';
// look for a match
echo preg_match("/ph+p/", $string, $matches);
?>
OUTPUT: 0
EG:Find a string with starting and ending letter separated by -?
<?php
// create a string
$string = '12345678';
// look for a match
echo preg_match("/1234-?5678/", $string, $matches);
?>
OUTPUT: 1
SPECIAL SEQUENCES
The backslash(\) is also used for sequences.
[Department of CSE] 23
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
foreach($matches[0] as $value)
{
echo $value;
}
?>
OUTPUT:abcefghijklmnopqrstuvwxyz0123456789
File handling is needed for any application. For some tasks to be done file needs to be
processed. File handling in PHP is similar as file handling is done by using any programming
language like C. PHP has many functions to work with normal files. Those functions are:
1) fopen() – PHP fopen() function is used to open a file. First parameter of fopen() contains name
of the file which is to be opened and second parameter tells about mode in which file needs to be
opened, e.g.,
<?php
$file = fopen(“demo.txt”,'w');
?>
“w” – Opens a file for write only. If file not exist then new file is created and if file
already exists then contents of file is erased.
“r” – File is opened for read only.
“a” – File is opened for write only. File pointer points to end of file. Existing data in file is
preserved.
“w+” – Opens file for read and write. If file not exist then new file is created and if file
already exists then contents of file is erased.
“r+” – File is opened for read/write.
“a+” – File is opened for write/read. File pointer points to end of file. Existing data in file
is preserved. If file is not there then new file is created.
“x” – New file is created for write only.
2) fread() –– After file is opened using fopen() the contents of data are read using fread(). It takes
two arguments. One is file pointer and another is file size in bytes,
E.g:
$filename = "demo.txt";
$file = fopen( $filename, 'r' );
$size = filesize( $filename );
$filedata = fread( $file, $size );
?>
[Department of CSE] 24
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
3) fwrite() – New file can be created or text can be appended to an existing file using fwrite()
function. Arguments for fwrite() function are file pointer and text that is to written to file. It can
contain optional third argument where length of text to written is specified, e.g.,
<?php
$file = fopen("demo.txt", 'w');
$text = "Hello world\n";
fwrite($file, $text);
?>
4) fclose() – file is closed using fclose() function. Its argument is file which needs to be closed,
E.G:
<?php
$file = fopen("demo.txt", 'r');
//some code to be executed
fclose($file);
?>
PHP Overwriting
Now that "newfile.txt" contains some data we can show what happens when we open an
existing file for writing. All the existing data will be ERASED and we start with an empty file.
<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "Mickey Mouse\n";
fwrite($myfile, $txt);
$txt = "Minnie Mouse\n";
fwrite($myfile, $txt);
fclose($myfile);
?>
Next, create an HTML form that allow users to choose the image file they want to upload:
<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
[Department of CSE] 25
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
Without the requirements above, the file upload will not work.
The type="file" attribute of the <input> tag shows the input field as a file-select control,
with a "Browse" button next to the input control
The form above sends data to a file called "upload.php", which we will create next.
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
?>
$target_dir = "uploads/" - specifies the directory where the file is going to be placed
$target_file specifies the path of the file to be uploaded
[Department of CSE] 26
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
The file input field in our HTML form above is named "fileToUpload".
Now, we want to check the size of the file. If the file is larger than 500KB, an error message is
displayed, and $uploadOk is set to 0:
The code below only allows users to upload JPG, JPEG, PNG, and GIF files. All other file types
gives an error message before setting $uploadOk to 0:
PHP 5 Cookies
A cookie is often used to identify a user.
What is a Cookie?
A cookie is often used to identify a user. A cookie is a small file that the server embeds on
the user's computer. Each time the same computer requests a page with a browser, it will send the
cookie too. With PHP, you can both create and retrieve cookie values.
Create Cookies With PHP
A cookie is created with the setcookie() function.
Syntax,
setcookie(name, value, expire, path, domain, secure, httponly);
[Department of CSE] 27
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
EG:
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
OUTPUT: Cookie named 'user' is not set!
<?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>
OUTPUT:
Cookie 'user' is set!
Value is: John Doe
[Department of CSE] 28
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
Delete a Cookie
To delete a cookie, use the setcookie() function with an expiration date in the past,
Eg:
<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
<html>
<body>
<?php
echo "Cookie 'user' is deleted.";
?>
</body>
</html>
MySQL Database
What is MySQL?
[Department of CSE] 29
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
Database Queries
A query is a question or a request.
We can query a database for specific information and have a recordset returned.
Eg:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Create database
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}
$conn->close();
echo "Connected successfully";
?>
The INSERT INTO statement is used to add new records to a MySQL table:
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
EG:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
[Department of CSE] 31
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
}
//Insert values into table
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', '[email protected]')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//display the result
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
[Department of CSE] 32
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
EG:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
EG:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
[Department of CSE] 34
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
connect1.php
<?php
$bid=$_POST['bid'];
$bname=$_POST['bname'];
$con=@mysql_connect("localhost","root","")or die(mysql-error());
echo "connected to database";
$db=@mysql_select_db("student",$con)or die(mysql-error());
echo "selected database";
$str="insert into book values($bid,'$bname')";
$res=@mysql_query($str)or die(mysql-error());
if($res>0)
{
echo "record created";
}
?>
XML BASICS:
Introduction to XML
What is XML?
Eg:
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
6.With XML, the author must define both the tags and the document structure.
XML is Extensible
Most XML applications will work as expected even if new data is added (or removed).
<note>
<date>2015-09-01</date>
<hour>08:30</hour>
<to>Adam</to>
<from>Jill</from>
<body>I will be home late</body>
</note>
Many computer systems contain data in incompatible formats. Exchange data between
incompatible systems (or upgraded systems), is a time-consuming tasks for web developers Large
amounts of data must be converted, and incompatible data is often lost.
XML stores data in plain text format. This provides a software- and hardware-independent way
of storing, transporting, and sharing data.
XML also makes it easier to expand or upgrade to new operating systems, new applications, or
new browsers, without losing data.
With XML, data can be available to all kinds of "reading machines" like people, computers, voice
machines, news feeds, etc.
When displaying XML data in HTML, you do not have to edit the HTML file when the data
changes.
With a few lines of JavaScript code, you can read an XML file and update the data content of any
HTML page.
This example loops through all <CD> elements in an XML file, and display the values of
<ARTIST> and <TITLE> elements in an HTML table:
[Department of CSE] 36
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
XML Tree
XML documents form a tree structure that starts at "the root" and branches to "the leaves"
An Example XML Document
XML documents use a self-describing and simple syntax:
All XML documents must contain a root element. This 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):
The terms parent, child, and sibling are used to describe the relationships between
elements.
Parent elements have children.
Children on the same level are called siblings (brothers or sisters).
All elements can have text content and attributes (just like in HTML).
[Department of CSE] 37
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
Eg:
<bookstore>
<book category="COOKING">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="WEB">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
The syntax rules of XML are very simple and logical. The rules are easy to learn, and easy to use.
Note: You might have noticed the XML declaration did not have a closing tag. This is not an
error. The declaration is not a part of the XML document itself.
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:
[Department of CSE] 38
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
<Message>This is incorrect</message>
<message>This is correct</message>
Note: "Opening and closing tags" are often referred to as "Start and end tags". Use whatever you
prefer. It is exactly the same thing.
text
attributes
other elements
or a mix of the above
Eg:<bookstore>
<book category="CHILDREN">
<title>Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="WEB">
<title>Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
[Department of CSE] 39
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
Eg:
<title>, <author>, <year>, and <price> have text content because they contain text.
<bookstore> and <book> have element contents, because they contain other elements.
<book> has an attribute (category="CHILDREN").
Naming Styles
There are no naming styles defined for XML elements. But here are some commonly used:
Camel case <firstName> Uppercase first letter in each word except the
first
XML documents often have a corresponding database. A good practice is to use the naming
rules of your database for the elements in the XML documents.
[Department of CSE] 40
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
XML Attributes
For a person's gender, the <person> element can be written like this:
<person gender="female">
<firstname>Anna</firstname>
<lastname>Smith</lastname>
</person>
XML Namespaces
XML Namespaces provide a method to avoid element name conflicts.
Name Conflicts
In XML, element names are defined by the developer. This often results in a conflict when
trying to mix XML documents from different XML applications.
This XML carries HTML table information:
Eg:
<table>
<tr>
<td>Apples</td>
<td>Bananas</td>
</tr>
</table>
This XML carries information about a table (a piece of furniture):
<table>
<name>African Coffee Table</name>
<width>80</width>
<length>120</length>
</table>
If these XML fragments were added together, there would be a name conflict. Both contain
a <table> element, but the elements have different content and meaning.A user or an XML
application will not know how to handle these differences.
[Department of CSE] 41
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
<h:tr>
<h:td>Apples</h:td>
<h:td>Bananas</h:td>
</h:tr>
</h:table>
<f:table>
<f:name>African Coffee Table</f:name>
<f:width>80</f:width>
<f:length>120</f:length>
</f:table>
XML Document Types
XML Validator
This help to check the syntax of your XML files, we have Valid XML Documents
A "valid" XML document is not the same as a "well formed" XML document.
A "valid" XML document must be well formed. In addition it must conform to a document type
definition.Rules that defines the legal elements and attributes for XML documents are called
Document Type Definitions (DTD) or XML Schemas.
There are two different document type definitions that can be used with XML:
[Department of CSE] 42
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
<!DOCTYPE note
[
<!ELEMENT note (to,from,heading,body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>
]>
!DOCTYPE note defines that the root element of the document is note
!ELEMENT note defines that the note element must contain the elements: "to, from,
heading, body"
!ELEMENT to defines the to element to be of type "#PCDATA"
!ELEMENT from defines the from element to be of type "#PCDATA"
!ELEMENT heading defines the heading element to be of type "#PCDATA"
!ELEMENT body defines the body element to be of type "#PCDATA"
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
<footer>&writer; ©right;</footer>
</note>
[Department of CSE] 43
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
XML Schema
An XML Schema describes the structure of an XML document, just like a DTD.
An XML document with correct syntax is called "Well Formed".
An XML document validated against an XML Schema is both "Well Formed" and "Valid".
XML Schema
XML Schema is an XML-based alternative to DTD:
<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>
</xs:element>
Another great strength about XML Schemas is that they are written in XML:
XML DOM
What is the XML DOM?
The XML DOM defines the objects and properties of all XML elements, and
the methods (interface) to access them.In other words: The XML DOM is a standard for how to
get, change, add, or delete XML elements.
DOM Nodes
According to the DOM, everything in an XML document is a node.
[Department of CSE] 45
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
DOM Example
The root node in the XML above is named <bookstore>. All other nodes in the document are
contained within <bookstore>.
The first <book> node holds four nodes: <title>, <author>, <year>, and <price>, which contains
one text node each, "Everyday Italian", "Giada De Laurentiis", "2005", and "30.00".
[Department of CSE] 46
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
The XML DOM views an XML document as a tree-structure. The tree structure is called
a node-tree. All nodes can be accessed through the tree. Their contents can be modified or
deleted, and new elements can be created.
The node tree shows the set of nodes, and the connections between them. The tree starts at the
root node and branches out to the text nodes at the lowest level of the tree:
The nodes in the node tree have a hierarchical relationship to each other.
The terms parent, child, and sibling are used to describe the relationships. Parent nodes have
children. Children on the same level are called siblings (brothers or sisters).
[Department of CSE] 47
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
The example below loops through all child nodes of <book>, and displays their names and values:
<html>
<head>
<script src="loadxmlstring.js"></script>
</head>
<body>
<script>
var text="<book>";
text=text+"<title>Everyday Italian</title>";
text=text+"<author>Giada De Laurentiis</author>";
text=text+"<year>2005</year>";
text=text+"</book>";
var xmlDoc=loadXMLString(text);
// documentElement always represents the root node
var x=xmlDoc.documentElement.childNodes;
for (i=0;i<x.length;i++)
{
document.write(x[i].nodeName);
document.write(": ");
document.write(x[i].childNodes[0].nodeValue);
document.write("<br>");
}
</script>
</body>
</html>
Output:
title: Everyday Italian
author: Giada De Laurentiis
year: 2005
Example explained:
[Department of CSE] 48
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
3. For each child node, output the node name and the node value of the text node
In the DOM, everything is a node. Element nodes do not have a text value.The text of an
element node is stored in a child node. This node is called a text node.The way to change the text
of an element, is to change the value of the child node (text node).
Eg:books.xml
<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="children">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="web">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>
<book category="web" cover="paperback">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
[Department of CSE] 49
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
Test.html
<!DOCTYPE html>
<html>
<head>
<script src="loadxmldoc.js">
</script>
</head>
<body>
<script>
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
x.nodeValue="Easy Cooking";
document.write(x.nodeValue);
</script>
</body>
</html>
Example explained:
test1.html
<!DOCTYPE html>
<html>
<head>
<script src="loadxmldoc.js">
</script>
</head>
<body>
<script>
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName('book');
x[0].setAttribute("category","food");
[Department of CSE] 50
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
document.write(x[0].getAttribute("category"));
</script>
</body>
</html>
output:
food
The following code fragment will remove the first <book> element from the loaded xml:
test2.html
<!DOCTYPE html>
<html>
<head>
<script src="loadxmldoc.js">
</script>
</head>
<body>
<script>
xmlDoc = loadXMLDoc("books.xml");
root = xmlDoc.documentElement;
currNode = root.childNodes[1];
removedNode = currNode.removeChild(currNode.childNodes[1]);
document.write("Removed node: " + removedNode.nodeName);
</script>
</body>
</html>
Output:
Removed node: title
[Department of CSE] 51
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
test3.html
<!DOCTYPE html>
<html>
<head>
<script src="loadxmldoc.js">
</script>
</head>
<body>
<script>
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.documentElement;
//create a book element, title element and a text node
newNode=xmlDoc.createElement("book");
newTitle=xmlDoc.createElement("title");
newText=xmlDoc.createTextNode("A Notebook");
//add the text node to the title node,
newTitle.appendChild(newText);
//add the title node to the book node
newNode.appendChild(newTitle);
y=xmlDoc.getElementsByTagName("book")[0]
//replace the first book node with the new node
x.replaceChild(newNode,y);
z=xmlDoc.getElementsByTagName("title");
for (i=0;i<z.length;i++)
{
document.write(z[i].childNodes[0].nodeValue);
document.write("<br>");
}
</script>
</body>
</html>
Output:
A Notebook
Harry Potter
XQuery Kick Start
Learning XML
This example loops through each <CD> element, and display the values of the <ARTIST> and
the <TITLE> elements in an HTML table:
[Department of CSE] 52
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
<!DOCTYPE html>
<html>
<style>
table,th,td
{
border : 1px solid black;
border-collapse: collapse;
}
th,td {
padding: 5px;
}
</style>
<body>
<table id="demo"></table>
<script>
var x,i,xmlhttp,xmlDoc,table;
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "cd_catalog.xml", false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
x = xmlDoc.getElementsByTagName("CD");
table="<tr><th>Artist</th><th>Title</th></tr>";
for (i = 0; i <x.length; i++)
{
table += "<tr><td>" +
x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue + "</td><td>" +
x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue + "</td></tr>";
}
document.getElementById("demo").innerHTML = table;
</script>
</body>
</html>
Eg:Refere class notes example(xml with external dtd and cascading style sheet)
All major browsers have a built-in XML parser to read and manipulate XML.The XML parser
converts XML into an XML DOM object that can be accessed with JavaScript.
XML Parser
The XML DOM contains methods to traverse XML trees, access, insert, and delete nodes.
However, before an XML document can be accessed and manipulated, it must be loaded into an
XML DOM object.
[Department of CSE] 53
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
An XML parser reads XML, and converts it into an XML DOM object that can be accessed with
JavaScript.
<!DOCTYPE html>
<html>
<body>
<script>
if (window.XMLHttpRequest)
{
xhttp=new XMLHttpRequest();
}
else // for IE 5/6
{
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET","books.xml",false);
xhttp.send();
xmlDoc=xhttp.responseXML;
document.write("XML document loaded into an XML DOM Object.");
</script>
</body>
</html>
Output:
XML document loaded into an XML DOM Object.
Code explained:
<!DOCTYPE html>
<html>
<body>
<script>
[Department of CSE] 54
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
text="<bookstore><book>";
text=text+"<title>Everyday Italian</title>";
text=text+"<author>Giada De Laurentiis</author>";
text=text+"<year>2005</year>";
text=text+"</book></bookstore>";
if (window.DOMParser)
{
parser=new DOMParser();
xmlDoc=parser.parseFromString(text,"text/xml");
}
else // Internet Explorer
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.loadXML(text);
}
document.write("XML string is loaded into an XML DOM Object");
</script>
</body>
</html>
Output:
XML string is loaded into an XML DOM Object
XML parsers normally parse all the text in an XML document.When an XML element is
parsed, the text between the XML tags is also parsed:
<message>This text is also parsed</message>
The term CDATA is used about text data that should not be parsed by the XML parser.
Characters like "<" and "&" are illegal in XML elements."<" will generate an error because the
parser interprets it as the start of a new element."&" will generate an error because the parser
interprets it as the start of an character entity.
Some text, like JavaScript code, contains a lot of "<" or "&" characters. To avoid errors script
code can be defined as CDATA.Everything inside a CDATA section is ignored by the parser.
<script>
<![CDATA[
function matchwo(a,b)
{
[Department of CSE] 55
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
A CDATA section cannot contain the string "]]>". Nested CDATA sections are not allowed.
The "]]>" that marks the end of the CDATA section cannot contain spaces or line breaks.
Parsing XML refers to going through XML document to access data or to modify data in one or
other way.
XML Parser provides way how to access or modify data present in an XML document. Java
provides multiple options to parse XML document. Following are various types of parsers which
are commonly used to parse XML documents.
Dom Parser - Parses the document by loading the complete contents of the document and
creating its complete hiearchical tree in memory.
SAX Parser - Parses the document on event based triggers. Does not load the complete
document into the memory.
The Document Object Model is an official recommendation of the World Wide Web Consortium
(W3C). It defines an interface that enables programs to access and update the style, structure,and
contents of XML documents. XML parsers that support the DOM implement that interface.
When to use?
[Department of CSE] 56
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
You need to move parts of the document around (you might want to sort certain elements,
for example)
You need to use the information in the document more than once
Advantages
The DOM is a common interface for manipulating document structures. One of its design goals is
that Java code written for one DOM-compliant parser should run on any other DOM-compliant
parser without changes.
DOM interfaces
The DOM defines several Java interfaces. Here are the most common interfaces:
When you are working with the DOM, there are several methods you'll use often:
<lastname>Gupta</lastname>
<nickname>vinni</nickname>
<marks>95</marks>
</student>
<student rollno="593">
<firstname>jasvir</firstname>
<lastname>singn</lastname>
<nickname>jazz</nickname>
<marks>90</marks>
</student>
</class>
DomParserDemo.java
package com.tutorialspoint.xml;
import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
try {
File inputFile = new File("input.txt");
DocumentBuilderFactory dbFactory
= DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputFile);
doc.getDocumentElement().normalize();
System.out.println("Root element :"
+ doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("student");
System.out.println("----------------------------");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
System.out.println("\nCurrent Element :"
+ nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println("Student roll no : " + eElement.getAttribute("rollno"));
System.out.println("First Name : "
[Department of CSE] 58
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
+ eElement.getElementsByTagName("firstname")
.item(0).getTextContent());
System.out.println("Last Name : "
+ eElement.getElementsByTagName("lastname")
.item(0).getTextContent());
System.out.println("Nick Name : "
+ eElement.getElementsByTagName("nickname").item(0)
.getTextContent());
System.out.println("Marks : "
+ eElement.getElementsByTagName("marks").item(0).getTextContent());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
Root element :class
----------------------------
[Department of CSE] 59
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
<supercars company="Ferrari">
<carname type="formula one">Ferrari 101</carname>
<carname type="sports">Ferrari 202</carname>
</supercars>
<luxurycars company="Benteley">
<carname>Benteley 1</carname>
<carname>Benteley 2</carname>
<carname>Benteley 3</carname>
</luxurycars>
</cars>
package com.tutorialspoint.xml;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
try {
File inputFile = new File("input.xml");
DocumentBuilderFactory docFactory =
DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder =
docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(inputFile);
Node cars = doc.getFirstChild();
Node supercar = doc.getElementsByTagName("supercars").item(0);
// update supercar attribute
NamedNodeMap attr = supercar.getAttributes();
Node nodeAttr = attr.getNamedItem("company");
nodeAttr.setTextContent("Lamborigini");
SAX (the Simple API for XML) is an event-based parser for xml documents.Unlike a DOM
parser, a SAX parser creates no parse tree. SAX is a streaming interface for XML, which means
that applications using SAX receive event notifications about the XML document being processed
[Department of CSE] 61
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
an element, and attribute, at a time in sequential order starting at the top of the document, and
ending with the closing of the ROOT element.
Reads an XML document from top to bottom, recognizing the tokens that make up a well-
formed XML document
Tokens are processed in the same order that they appear in the document
Reports the application program the nature of tokens that the parser has encountered as
they occur
The application program provides an "event" handler that must be registered with the
parser
As the tokens are identified, callback methods in the handler are invoked with the relevant
information
When to use?
You can process the XML document in a linear fashion from the top down
The document is not deeply nested
You are processing a very large XML document whose DOM tree would consume too
much memory.Typical DOM implementations use ten bytes of memory to represent one
byte of XML
The problem to be solved involves only part of the XML document
Data is available as soon as it is seen by the parser, so SAX works well for an XML
document that arrives over a stream
Disadvantages of SAX
ContentHandler Interface
This interface specifies the callback methods that the SAX parser uses to notify an application
program of the components of the XML document that it has seen.
[Department of CSE] 62
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
void ignorableWhitespace( char[] ch, int start, int length) - Called when a DTD is
present and ignorable whitespace is encountered.
void processingInstruction(String target, String data) - Called when a processing
instruction is recognized.
void setDocumentLocator(Locator locator)) - Provides a Locator that can be used to
identify positions in the document.
void skippedEntity(String name) - Called when an unresolved entity is encountered.
void startPrefixMapping(String prefix, String uri) - Called when a new namespace
mapping is defined.
void endPrefixMapping(String prefix) - Called when a namespace definition ends its
scope.
Attributes Interface
This interface specifies methods for processing the attributes connected to an element.
[Department of CSE] 63
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
SAXParserDemo.java
package com.tutorialspoint.xml;
import java.io.File;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
try {
File inputFile = new File("input.txt");
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
UserHandler userhandler = new UserHandler();
saxParser.parse(inputFile, userhandler);
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Override
public void startElement(String uri,
String localName, String qName, Attributes attributes)
throws SAXException {
if (qName.equalsIgnoreCase("student")) {
String rollNo = attributes.getValue("rollno");
System.out.println("Roll No : " + rollNo);
} else if (qName.equalsIgnoreCase("firstname")) {
bFirstName = true;
} else if (qName.equalsIgnoreCase("lastname")) {
bLastName = true;
} else if (qName.equalsIgnoreCase("nickname")) {
bNickName = true;
[Department of CSE] 64
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
}
else if (qName.equalsIgnoreCase("marks")) {
bMarks = true;
}
}
@Override
public void endElement(String uri,
String localName, String qName) throws SAXException {
if (qName.equalsIgnoreCase("student")) {
System.out.println("End Element :" + qName);
}
}
@Override
public void characters(char ch[],
int start, int length) throws SAXException {
if (bFirstName) {
System.out.println("First Name: "+ new String(ch, start, length));
bFirstName = false;
} else if (bLastName) {
System.out.println("Last Name: " + new String(ch, start, length));
bLastName = false;
} else if (bNickName) {
System.out.println("Nick Name: " + new String(ch, start, length));
bNickName = false;
} else if (bMarks) {
System.out.println("Marks: " + new String(ch, start, length));
bMarks = false;
}
}
}
Output:
Roll No : 393
First Name: dinkar
Last Name: kad
Nick Name: dinkar
Marks: 85
End Element :student
Roll No : 493
First Name: Vaneet
Last Name: Gupta
Nick Name: vinni
Marks: 95
End Element :student
Roll No : 593
[Department of CSE] 65
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
XML Validator
XML validator will stop execution if syntax error found in the .XML file ie..,Errors in XML
documents will stop your XML applications.
The W3C XML specification states that a program should stop processing an XML document
if it finds an error. The reason is that XML software should be small, fast, and compatible. HTML
browsers are allowed to display HTML documents with errors (like missing end tags).
Eg2:
Try to validate incorrect XML :
<?xml version="1.0" encoding="UTF-8"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</pheading>
<body>Don't forget me this weekend!</body>
</note>
XSL
Before learning XSLT, we should first understand XSL which stands for EXtensible
Stylesheet Language. It is similar to XML as CSS is to HTML.
[Department of CSE] 66
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
In case of HTML document, tags are predefined such as table, div, and span; and the browser
knows how to add style to them and display those using CSS styles. But in case of XML
documents, tags are not predefined. In order to understand and style an XML document, World
Wide Web Consortium (W3C) developed XSL which can act as XML based Stylesheet
Language. An XSL document specifies how a browser should render an XML document.
XSLT − used to transform XML document into various other types of document.
XPath − used to navigate XML document.
XSL-FO − used to format XML document.
What is XSLT
XSLT, Extensible Stylesheet Language Transformations, provides the ability to transform XML
data from one format to another automatically.
An XSLT stylesheet is used to define the transformation rules to be applied on the target XML
document. XSLT stylesheet is written in XML format. XSLT Processor takes the XSLT
stylesheet and applies the transformation rules on the target XML document and then it generates
a formatted document in the form of XML, HTML, or text format. This formatted document is
then utilized by XSLT formatter to generate the actual output which is to be displayed to the end-
user.
Advantages
XSLT Syntax
we have the following sample XML file, students.xml, which is required to be transformed into a
well-formatted HTML document.
Students.xml
<?xml version = "1.0"?>
<class>
[Department of CSE] 67
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
We need to define an XSLT style sheet document for the above XML document to meet the
following criteria −
Create an XSLT document to meet the above requirements, name it as students.xsl and save it in
the same location where students.xml lies.
students.xsl
<html>
<body>
<h2>Students</h2>
[Department of CSE] 68
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
<xsl:for-each select="class/student">
<tr>
<td>
<!-- value-of processing instruction
process the value of the element matching the XPath expression
-->
<xsl:value-of select = "@rollno"/>
</td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Update student.xml document with the following xml-stylesheet tag. Set href value to students.xsl
[Department of CSE] 69
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
students.xml
[Department of CSE] 70
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
When you subscribe to a news feed with a news reader you will receive the content in a
way that is very similar to email. When you launch your news reader software it will check your
subscriptions and fetch any new content. This will usually contain information such as the date
and headline, author, article summary and a web link to the source article as a web page. It can
also be used to embed media files such as podcasts, streaming radio and video.
The strength of using a news feed comes from how it is managed and customised. As a
subscriber you are free to assemble as many news feeds as you like. And you can choose to use
only the sources that interest you. For example you could choose to subscribe to the Technology
section If you use a web browser such as Firefox you can also subscribe to news feeds as
Live Bookmarks. With Live Bookmarks you will see the item titles of the news feed in your
bookmarks. This way you can keep details of new content within your web browser and stay up to
date without even visiting the web site.
The good news is that adding a news feed to your own web site is quite straightforward. For
example we created the news feed are used to help web browsers and other software
automatically discover the news feed when the web site is visited. However, most of the news
feeds published by our clients are created automatically as a to manage their news distribution.
Blogger automatically creates its news feed in Atom format.
The format of the news feed published by a third party service doesn’t really make much
difference though. Atom formatted news feeds were originally developed to address technical
issues which existed with the emerging standards for RSS news feeds. They also contain many
features that aren’t available in RSS 2.0 and as such are sometimes considered a superior format.
However the RSS format is easier to implement and more widely recognised. RSS is also used as
a general way to describe all types of news feed and is taken as the abbrevitation of Really Simple
Syndication, Rich Site Summary or RDF Site Summary depending on who you talk to.
RSS
RSS stands for both Rich Site Summary and Really Simple Syndication but it always refers to the
same technology.
Most news sites (including virtually all blogs) will publish what is called an RSS feed which is
regularly updated with the latest available headlines and/or articles.
The RSS feed is not human readable. It is an format which is designed to be read by machines
rather than humans.
[Department of CSE] 71
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
Reading RSS
To take advantage of an RSS feed you would use a piece of software called an RSS aggregator.
Most of them are very similar to email client programs, but instead of incoming emails, they
display news from various sources (from all the feeds you have registered with, or "subscribed to"
as is commonly said but it has nothing to do with money). Unread news typically appear in bold,
just as unread emails do.
An RSS aggregator makes it very convenient to follow up on news from a large number of
sources in a single place is an example of an RSS Reader.
Just like there is webmail, there are also are web-RSS-aggregators. it is such an online aggregator.
Il allows you to track all your news from a single place you can access with a regular web
browser.
Also, most modern web browsers will also handle RSS feeds, but in a limited manner. They will
use an RSS feed as a dynamic bookmark folder with automatic bookmarks to all the news in the
feed. Unlike aggregators, browsers will not save the news if you don't check on them every day.
Finally, on a more professional level, some websites will aggregate news from different sources
onto a single site. Hence the "syndication" in the name.
Producing RSS
While you could theoretically write an RSS file by hand and update it regularly, writing XML
manually is a tedious task.
Most RSS feeds are produced automatically by the same content management software which
also generates the web pages dynamically. All blog tools for example can generate RSS feeds on
the fly. is an example of such a blog tool.
Distributing RSS
Whether you generate your RSS by hand or have a tool generate it automatically, you need to
make it available on the web for users (and their "client" software) to consume.
Different flavours
There are different versions of RSS in use. RSS 2.0 is the most common. It is used for news/blog
feeds as well as for Podcasting.
A newer format, called Atom, is a more standardized way of providing XML content updates.
However, it has not gotten wide acceptance yet outside of the blog communities. (Again, almost
all blog tools can generate an Atom feed on the fly.)
[Department of CSE] 72
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
RSS 2.0
RSS 2.0 has the widest acceptance of any feed format. Much of that has to do with the defacto use
of it by WordPress, but it is also the one variety of RSS format that seems to have solved some of
the problems presented by earlier versions. Of the two feed types, RSS is most widley used but
also has signifigant downfalls.
For one, RSS does not allow any well-formed XML markup in it’s content. This is very bad when
it comes to using RSS-syndicated content elsewhere. In fact, it only supports plain text or escaped
HTML which, without getting into the technical issues surrounding that, simply means it’s very
difficult to work with.
RSS has only three required fields on a per item basis- title, link and description. There are a
variety of optional fields but some key features, such as a “last updated” field are missing.
Atom 1.0
Atom is a relatively recent spec and is much more robust and feature-rich than RSS. For instance,
where RSS requires descriptive fields such as title and link only in item breakdowns, Atom
requires these things for both items and the full feed.
Atom feeds provide an “updated” field which means that any feeds that are modified have a
timestamp associated with them. Trust me when I say I find this useful.
A cool feature of Atom has to do with autodiscovery. Most of the time, if you point your browser
to a feed-enabled website, autodiscovery kicks in and the browser alerts you in its own unique
way to the presence of a feed. The same thing happens when you point a feed reader to a feed-
enabled website as opposed to the specific feed itself. While feed autodiscovery has been around
for a long time, Atom feeds actually contain a self pointer autodiscovery URL which is highly
unique from RSS itself.
There’s quite a lot different in terms of the two specs. If you’re really interested in discovering the
technical differences between the two, I encourage you to read . He really nails it very well.
RSS vs Atom . which one is better ?
RSS is a family of formats used to publish frequently updated works—such as blog entries, news
headlines, audio, and video—in a standardized format.
[Department of CSE] 73
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
An RSS document which is called a “feed”, “web feed” ,or “channel” includes full or summarized
text, plus metadata such as publishing dates andauthorship.RSS feeds benefit publishers by letting
them syndicate content automatically
RSS Example
<?xml version=”1.0″ encoding=”UTF-8″ ?>
<rss version=”2.0″>
<channel>
<title>RSS Title</title>
<description>This is an example of an RSS feed</description>
<link>http://www.someexamplerssdomain.com/main.html</link>
<lastBuildDate>Mon, 06 Sep 2010 00:01:00 +0000 </lastBuildDate>
<pubDate>Mon, 06 Sep 2009 16:45:00 +0000 </pubDate>
<ttl>1800</ttl>
<item>
<title>Example entry</title>
<description>Here is some text containing an interesting description.</description>
<link>http://www.wikipedia.org/</link>
<guid>unique string per item</guid>
<pubDate>Mon, 06 Sep 2009 16:45:00 +0000 </pubDate>
</item>
</channel>
</rss>
Atom
The advent of the ATOM syndication standard was a response to the design flaws of the
RSS standard. The primary advantage of the ATOM is its adaptation as the IETF standard.
The Atom Syndication Format is an XML language used for web feeds, while the Atom
Publishing Protocol (AtomPub or APP) is a simple HTTP-based protocol for creating and
updating web resources.ATOM code has been built from the ground with modularity in mind.
Therefore, a great majority of its code is reusable even with other XML vocabularies like RSS
<feed xmlns="http://www.w3.org/2005/Atom">
<title>Example Feed</title>
<subtitle>A subtitle.</subtitle>
[Department of CSE] 74
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
<id>urn:uuid:60a76c80-d399-11d9-b91C-0003939e0af6</id>
<updated>2003-12-13T18:30:02Z</updated>
<entry>
<id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id>
<updated>2003-12-13T18:30:02Z</updated>
<summary>Some text.</summary>
<author>
<name>John Doe</name>
<email>[email protected]</email>
</author>
</entry></feed>
[Department of CSE] 75
PERI IT
PERIIT
CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE
category Category
channel Feed
copyright Rights
description Subtitle
generator Generator
guid Id
image Logo
item entry
Link link
Title title
Ttl –
[Department of CSE] 76