BCA245 - Web Technology Laboratory
BCA245 - Web Technology Laboratory
BCA245 - Web Technology Laboratory
S.Y.B.C.A.(Science)
SEMESTER IV
BCA-245
LAB COURSE – II
Assignments
Name:________________________________________________
College Name:_________________________________________
1
From the Chairman’s Desk
It gives me a great pleasure to present this workbook prepared by the Board of studies in
Computer Applications.
The workbook has been prepared with the objectives of bringing uniformity in implementation
of lab assignments across all affiliated colleges, act as a ready reference for both fast and slow
learners and facilitate continuous assessment using clearly defined rubrics.
The workbook provides, for each of the assignments, the aims, pre-requisites, related
theoretical concepts with suitable examples wherever necessary, guidelines for the faculty/lab
administrator, instructions for the students to perform assignments and a set of exercises
divided into three sets.
I am thankful to the Chairman of this course and the entire team of editors. I am also thankful
to the reviewers and members of BOS, Mr. Rahul Patil and Mr. Arun Gangarde. I thank all
members of BOS and everyone who have contributed directly or indirectly for the preparation
of the workbook.
Constructive criticism is welcome and to be communicated to the Chairman of the Course and
overall coordinator Mr. Rahul Patil. Affiliated colleges are requested to collect feedbacks from
the students for the further improvements.
I am thankful to Hon. Vice Chancellor of Savitribai Phule Pune University Prof. Dr. Nitin
Karmalkar and the Dean of Faculty of Science and Technology Prof. Dr. M G Chaskar for their
support and guidance.
SPPU, Pune
2
Editors:
Compiled By:
Reviewed By:
3
Introduction
Students are expected to carry this book every time when they come to the labfor
computer science practical.
4
Not done 0
Incomplete 1
Late Complete 2
Needs improvement 3
Complete 4
Well Done 5
1. Explain the assignment and related concepts in around ten minutes using
whiteboard ifrequired or by demonstrating the software.
2. You should evaluate each assignment carried out by a student on a scale of 5 as
specifiedabove by ticking appropriate box.
3. The value should also be entered on assignment completion page of the
respectiveLabcourse.
You have to ensure appropriate hardware and software is available to each student
in the Lab.
The operating system and software requirements on server side and also client
side are as given below:
5
Table of Contents
6
Assignment Completion Sheet
1 PHP Programming
2 Use of Functions
3 Use of Arrays
Total Out of 30
Total Out of 15
7
CERTIFICATE
Mr./Ms._________________________________________
Instructor H.O.D./Coordinator
8
Assignment Number 1: PHP Programming
Pre-requisite:
Students must read theory and syntax for solving programmes before his/her
practical slot.
Solve SET A, B or C assigned by instructor in allocated slots only.
Theory:
PHP is server-side scripting language which is used to create dynamic web page. The
long form of PHP is “Hypertext Preprocessor”. Which is recursive. A script is a set of
programming instructions that is interpreted at runtime. A scripting language that
interprets scripts at runtime. The purpose of the scripts is usually to enhance the
performance or perform routine tasks for an application. PHP is a server side scripts that
is interpreted in the server.
Reading:
https://www.tutorialspoint.com/php/php_tutorial.pdf
https://sites.harding.edu/fmccown/php_introduction.pdf
https://www.studytonight.com/php/introduction-to-php
In PHP, a variable starts with the $ sign, followed by the name of the variable:
Example
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>
After the execution of the statements above, the variable $txt will hold the value Hello
world!, the variable $x will hold the value 5, and the variable $y will hold the value 10.5.
9
A variable can have a short name (like x and y) or a more descriptive name (age,
carname, total_volume).
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)
Output Variables
The PHP echo statement is often used to output data to the screen.
The following example will show how to output text and a variable:
Example
<?php
$txt = "W3Schools.com";
echo "I love $txt!";
?>
10
break;
case value 2: //code block 2;
break;
case value 3: //code block 3;
break;
……
default: //default code block;
endswitch:
Loops:
Loops are used to execute same block of statements specific number of times. There are 4
types of loops in PHP.
1) While loop:while loop will execute block of code until certain condition is meet.
Syntax:
while( expression)
{// code block to be executed
}
Example
<?php
$i=1;
while($i=10)
{ echo($i<=10)
{
echo $i.” “;
$i++;
}
?>
Output: 1 2 3 4 5 6 7 8 9 10
2) do..while:This loop works same as while loop , except that the expression is
evaluated at the end of each iteration.
Syntax:
do {
//code block to be executed
}while(expression);
11
example
<?php
$i=1;
do
{ echo($i<=10)
{
echo $i.” “;
$i++;
} while($i=10);
?>
Output:
1 2 3 4 5 6 7 8 9 10
3) for: The for loop is used when you know in advance how many times the script
should run.
Syntax
Parameters:
Example
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
4) foreach Loop: The foreach loop - Loops through a block of code for each
element in an array.
Syntax:
12
foreach ($array as $value) {
code to be executed;
}
For every loop iteration, the value of the current array element is assigned to $value and
the array pointer is moved by one, until it reaches the last array element.
Example
<?php
$colors = array("red", "green", "blue", "yellow");
Exercises
1. Write a PHP script to get the PHP version and configuration information
2. Write a PHP script to display student information on web page.
3. Write a PHP script to script to display time table of your class( use HTML table
tags in echo).
1. Write a PHP script to declare three variables and print maximum among them.
2. Write a PHP script to check number 153 is Armstrong or not.
3. Write a PHP script to check whether accepted number is prime or not.
Assignment Evaluation
0: Not Done [ ] 1: Incomplete [] 2: Late Complete []
3: Needs Improvement [] 4: Complete [] 5: WellDone []
13
Assignment Number 2: Functions
Aim:To study user defined and library functions and their implementation in
programs.
Pre-requisite:
Demonstration of user defined and library functions with their syntax using
simple programmes
Students must read theory and syntax for solving programmes before his/her
practical slot.
Solve SET A, B or C assigned by instructor in allocated slots only.
Theory:
PHP is web scripting language implies that PHP is used to write web scripts,
not the stand-alone applications. That is programs are executed through a web
browser. PHP scripts run only after an event occurs.
Examplehello.php
<html> Output:
<head> Hello, world!
<title>Look Out
World</title>
</head>
<body>
<?php echo 'Hello,
world!' ?>
</body>
</html>
User-defined functions
A function is a block of statements that can be used repeatedly in a
program. A function will not execute immediately when a page loads.
A function will be executed by a call to the function. A function may
be defined using syntax such as the following:
functionfunction_name([argument_list…])
{
[statements]
[return return_value;]
}
Any valid PHP code may appear inside a function, even other
14
functions and class definitions. The variables you use inside a
function are, by default, not visible outside that function.
Example:
<?ph Output :
p Hello
msg("Hello"); // calling a
function function msg($a) //
defining a function
{
echo $a;
}
?
>
Default parameters
You can give default values to more than one argument, but once you
start assigning default values, you have to give them to all arguments
that follow as well.
<?php Output:
function display($greeting, Hello
$message=‖GoodDay‖)
{ Good Day
echo $greeting;
echo―<br>‖;
echo $message;
}
display(―Hello‖);
?>
Variable parameters
You can set up functions that can take a variable number of
arguments. Variable number of arguments can be handled with
these functions:
func_num_args( ) :
Returns the number of
arguments passed
func_get_arg() :
Returns a single
argument
func_get_args( ) :
Returns all arguments
in anarray
15
<?ph Output:
p echo―Passing3arg.toxconcat<br>‖;
Passing 3
echo―Resultis…‖;
arg. to
xconcat(―How‖,‖are‖,‖you‖);
xconcat
function xconcat() Result is
…How are
{ you
$ans= ―‖;
$arg = func_get_args( );
for ($i=0; $i<func_num_args( );
$i++ )
{
?
> $ans.= $arg[$i].‖―;
Missing parameters
}
When using default arguments, any defaults should be on the right side
echo $ans;
of any non default arguments, otherwise, things will not work as
expected.
}
<?p Output :
hp function makecoffee ($type
Making
="Nescafe")
a cup of
{ Nescafe.
return "Making a cup Making
of$type<br>"; a cup of
espresso
}
? .
> echo makecoffee ();
echo makecoffee
Variable functions
Assign("espresso");
a variable the name of a function, and then treat that variable as though it
is the name of a function.
<?php Output:
$varfun='fun1'; Function one
$varfun( ); Function two
$varfun='fun2'; Function three
$varfun( );
Anonymous functions
The function that does not possess any names are called anonymous functions.
Such functions are created using
create_function( ) built-in function. Anonymous functions are also called as
lambda functions.
16
<?p Output
hp : 30
$fname=create_functio
n('$a,$b',
'$c = $a + $b;
return $c;'); echo
$fname(10,20);
?
>
Strings
A string of characters is probably the most commonly used data
type when developing scripts, and PHP provides a large library of
string functions to help transform, manipulate, and otherwise manage
strings.
17
strlen() The strlen() function <?php
returns length of the int strlen (string $str="INDIA";
string. $string ) $l=strlen(
$str);
echo $l;
?
>
5
strpos() Find the position of the <?php
first occurrence of a Strpos(string, $str="INDIA";
string inside another search) $p=strpos($str,
string (case- sensitive). If ‖I‖); echo$p;
no match is found, it will ?
return FALSE. >
0
strrpos() Find the position of the <?php
last occurrence of a Strrpos(string, $str="INDIA";
string inside another serach) $p=strrpos($str
string (case- sensitive), if ,‖I‖); echo$p;
no match is found, it will ?
return FALSE. >
3
str_replace() Replace all occurrences Str_replace(search, <?php
of the search string with replace,string) echo str_replace("world",
the replacement string "Dolly", "Hello world!"); //
(case- sensitive) outputs Hello Dolly!
?>
strcmp( ) If both strings are equal, Strcmp (String1, If(strcmp(―India‖,‖india‖)== 0)
strcmp ( ) return 0 String2) Echo ―Both string are
equal‖; Else
Echo―Both string
arenotequal‖;
strstr( ) Find the first occurrence Strstr(sourceString,
of a string inside another subString)
string
(case-sensitive)
substr( ) Returns the substring from Substr(string, start,
string that begins at start length)
and is of length
characters long.
Exercises
1. Write a PHP script to accept the number from user and Write a php function to
calculate the factorial of a number (a non-negative integer). The function accepts
the number as an argument.
18
2. Design a HTML form to accept a string. Write a php function to reverse a string.
3. Design a HTML form to accept a string. Write a PHP function that checks
whether a passed string is a palindrome or not?
1. Design a HTML page to accept a number and write a PHP script to display that
number in words e.g. 123 - one two three
2. Design a HTML form to accept a string. Write a PHP script for the following. a)
Write a function to count the total number of Vowels from the script. b) Show the
occurrences of each Vowel from the script.
3. Write a PHP script for the following: a) Design a form to accept two numbers
from the users. b) Give option to choose an arithmetic operation (use Radio
Button). c) Display the result on next form. d) Use concept of default parameter.
1. Design a HTML form to accept email address from the user. Write a PHP
function using regular expressions check for the validity of entered email-id. The
@ symbol should not appear more than once. The dot (.) can appear at the most
once before @ and at the most twice or at least once after @ symbol. The
substring before @ should not begin with a digit or underscore or dot or @ or any
other special character. (Use explode and ereg function.)
2. Write a PHP script for the following: Design a form to accept the details of 5
different items, such as item code, item name, units sold, rate. Display the bill in
the tabular format. Use only 4 text boxes. (Hint : Use of explode function.)
3. Write a PHP script for the following: Design a form to accept two strings.
Compare the two strings using both methods (= = operator & strcmp function).
Append second string to the first string. Accept the position from the user; from
where the characters from the first string are reversed. (Use radio buttons)
Assignment Evaluation
0: Not Done [ ] 1: Incomplete [] 2: Late Complete []
3: Needs Improvement [] 4: Complete [] 5: WellDone []
Signature of Instructor: Date:
19
Assignment Number 3:Arrays
Pre-requisite:
Students must read theory and syntax for solving programmes before his/her
practical slot.
Solve SET A, B or C assigned by instructor in allocated slots only.
Theory:
Indexed array / Numeric array : An array with a numeric index starting with 0.
For example,
$cars=array(“Volvo”,”BMW”,”Toyota”);
Initializing an indexed array,
$cars[0]= “Volvo”;
$cars[1]= “BMW”;
$cars[2]= “Toyota”;
Associative array : An array which have strings as keys which are used to access the
values.
For example,
$age=array(“Peter”=>”35”,”Ben”=>”37”,”Joe”=>”43”);
Initializing an Associative array,
$age[ ‘Peter’ ]=”35”;
$age[ ‘Ben’ ]=”37”;
$age[ ‘Joe’ ]=”43”;
20
Multidimensional array : Arrays containing one or more arrays.
For example,
$cars=array(
array(“Volvo”,22,18),
array(“BMW”,15,13),
array(“Saab”,5,2),
array(“Land Rover”,17,15)
);
21
PHP executes the body echo “Student $value \n”;
of the loop once for }
each Output
element of $students, Student A
with Student B
$value set to the Student C
current element. Student D
For associative array :
$students=array(‘Name’=>‘a’,’Roll_No’ =>
100,‘Class’=>’SYBCA’);
foreach($students as $key=>$value)
{
echo “Student’s $key is : $value \n”;
}
Student’s Name is : A
Student’s Roll_No is : 100
Student’s Class is : SYBCA
array_push() These functions are array_push(a);
array_pop() used to treat an array array_pop(a);
like a stack .
array_shift() These functions are array_shift();
array_unshift() used to treat an array array_unshift();
like a queue.
Exercises
3. Declare array. Reverse the order of elements, making the first element last and
last element first and similarly rearranging other array elements.[Hint :
array_reverse()]
2. Write a menu driven program to perform the following stack related operations.
22
a) Insert an element in stack.
b) Delete an element from stack.[Hint: array_push(), array_pop()]
3. Write a menu driven program to perform the following queue related operations
a) Insert an element in queue
b) Delete an element from queue
c) Display the contents of queue
Assignment Evaluation
0: Not Done [ ] 1: Incomplete [] 2: Late Complete []
3: Needs Improvement [] 4: Complete [] 5: WellDone []
23
Assignment Number 4: Inheritance and Interfaces
Aim: To study object oriented concepts with their use in programming language.
Pre-requisite:
Students must read theory and syntax for solving programmes before his/her
practical slot.
Solve SET A, B or C assigned by instructor in allocated slots only.
Theory:
24
“Public member”; class maths
{
public $num;
public function multi()
{
return $this->num*2;
}
}
$math=new maths;
$math->num=2;
echo $math->multi();
?>
Output : 4
protected Protected Private Protected:
$protectedmember = <?php
“Protected Member”; class maths
Private {
$privatemember= protected $num;
“Private Member public function setnum($num)
{
$this->num=$num;
}
public function multi()
{
return $this->num*2;}}
class add extends maths
{
public function addtwo()
{
$new_num=$this->num + 2;
return ($new_num);
}
}
$math=new add;
$math->setnum(14);
echo $math->addtwo();
?>
Output : 16
class extendedClass Inheritance It is the <?php
extends classname ability of PHP to extend class myclass
classes that inherit the {
characteristics of the //property declaration
parent class. It is not public $var=’a default value’;
possible to extend //method declaration
multiple classes ; a public function desplayVar()
class can only inherit {
from one base class. echo $this->var;
}
}
class extendedClass extends myclass
25
{
//redefine the parent method
function displayVar()
{
echo “Extending Class”;
parent::displayVar();
}
}
$extend =new extendedClass();
$extend->displayVar();
?>
Output :
Extending class
a default value
Overriding When we give a <?php
function in the child class Hello
class the same name as {function getMessage()
a function in the parent { return ‘Hello World !’;}
class, this concept is }
called function class Goodbye extends Hello
overriding. Any method {function getMessage(){
or class that is declared return ‘Goodbye World!’;}}
as final can not be $hello=&new Hello();
overridden or inherited Echo $hello->getMessage().’<br/>’;
by another class $goodbye = &new Goodbye();
Echo $goodbye->getMessage().
’<br/>’;?>
Output:
Hello World!
Goodbye World!
void _construct Constructor is a <?php
([mixed $args [, function which is called class Student
$....]]) right after a new object {
is created. var $name;
var $address;
var $phone;
//This is constructor
function student()
{
this->name=”abc”;
this->address=”pqr”;
this->phone=1111;
}
function printstudentinfo()
{
echo this->name . ”\n”;
echo this->address . ”\n”;
echo this->phone . “\n”;
}
}
26
$stud =new student();
$stud->printstudentinfo();
$stud=NULL;
?>
void _destruct (void) Destructor is a function <?php
which is called right class Student
after you release an {
object. var $name;
var $address;
var $phone;
//This is constructor
function _construct()
{
this->name=”abc”;
this->address=”pqr”;
this->phone=1111;
}
function _destruct()
{
echo “Student Object
Released”;}
function printstudentinfo()
{
Echo this->name . ”\n”;
echo this->address . ”\n”;
echo this->phone . “\n”;
}
}
$stud =new student();
$stud->printstudentinfo();
$stud=NULL;
?>
class_exist() Introspection We can $class = class_exists(classname);
use this function to
determine whether a
get_declared_classes() class exists.
This function returns $classes = get_declared_classes();
array of defined classes
and checks if the class
get_class_methods() name is in returned $methods =
array. get_class_methods(classname);
27
This function is used to
find the class’s parent
class.
s_object() Is_object function is $obj= is_obj(var);
used to make sure that
it is object.
get_class() get_class() function is $classname= get_class(object);
used to get the class to
which an object
belongs and to get class
name
method_exists() This function is used to $method_exists=method_exists(object
check if method on an ,method);
object exists .
get_object_vars() This function returns an
array of properties set $array=get_object_vars(object);
in an object
serialize() Serialization Serializing $encode=serialize(something)
an object means
converting it to a byte
stream representation
that can be stored in a
file. returns a string
containing a byte-
stream representation of
the value that can be
stored anywhere
unserialize() Takes a single $something = unserialize (encode);
serialized variable and
converts it back to PHP
value.
Interfaces An interface is declared Example of an interface
similar to a class but class duck
only include function { function quack()
prototypes (without {
implementation) and echo “quack,quack,qk, qk…”;
constants. When a class }
uses an interface the }
class must define all the Interface birds
methods / function of {
the interface otherwise function breath();
the PHP engine will function eat();
give you an error. The }
interface’s function Class duck implements birds
/methods cannot have { function quack()
the details filled in. that {
is left to the class that echo “quack,quack,qk, qk…”;
uses the interface. }
}
function breath()
28
{
echo “duck is breathing”;
}
function eat()
{
echo “ duck is eating”;
}
Encapsulation Encapsulation is an <?php
ability to hide details of class A
implementation. {
function check()
{
if(isset ($this))
{
echo “$this is defined (“;
echo get_class($this);
echo “)\n”;
}
else
{
echo “this is not defined”;
}
}
}
class B
{
function bcheck()
{
A::check();
}
}
$a=new A();
$a->check();
A::check();
$b=new B();
$b->bcheck();
B::bcheck();
?>
Output:
$this is defined(a)
$this is not defined
$this is defined(b)
$this is not defined
29
Exercises
1) Write a PHP program to define Interface shape which has two method as area()
and volume (). Define a constant PI. Create a class Cylinder implement this
interface and calculate area and Volume.
2) a) Write a PHP script to create a Class shape and its subclass triangle, square and
display area of the selected shape.( use the concept of Inheritance)
Display menu (use radio button)
a) Triangle
b) Square
c) Rectangle
d) Circle
3) Write class declarations and member function definitions for Teacher (code,
name, qualification). Derive teach_account(account_no,joining_date) from
Teacher and teach_sal(basic_pay, earnings, deduction) fromteach_account.Write
a menu driven program
a) To build a master table
b) To sort all entries
c) To search an entry
d) Display salary of all teachers.
4) Write PHP script to demonstrate the concept of introspection for examining
object.
30
2) Create an interface for the classes that handle properties, having methods to
setProperty() andgetProperty() methods. Create another interface HOME having
setHasApartment($bool) andgetHasSociety() methods which is boolean. Create
class Bunglow with two properties set and getand hasGarden property and
implement the two interfaces.
Assignment Evaluation
0: Not Done [ ] 1: Incomplete [] 2: Late Complete []
31
Assignment Number 5 : Accessing Databases (PostgreSQL)
Pre-requisite:
Students must read theory and syntax for solving programmes before his/her
practical slot.
Solve SET A, B or C assigned by instructor in allocated slots only.
Create appropriate database for the question asked. i.e. Create the relations
accordingly, so that the relationship is handled properly and the relations are in
normalized form (3NF).
Get database checked from the instructor before you start writing PHP script.
Insert sufficient number of records into the database. Make sure result set of any
query will be non-empty.
Theory:
Following example shows various functions that used for PostgreSQL database
manipulation while writing PHP scripts. With these functions, scripts written by us will
access the database for different purposes such as inserting new data, removing data, and
fetching data from database. Or even updating the same.
32
<?php
$dbconn = pg_connect("host=localhost dbname=demo user=sybca1 password=sybca1")
or die('Could not connect: ' . pg_last_error());
$query = 'SELECT * FROM employee';
$result = pg_query($query) or die('Query failed: ' . pg_last_error());
echo "<table>\n";
while ($temp = pg_fetch_array($result, null, PGSQL_ASSOC)) {
echo "\t<tr>\n";
foreach ($temp as $col_value) {
echo "\t\t<td>$col_value</td>\n";
}
echo "\t</tr>\n";
} Reference: - https://www.php.net/manual/
echo "</table>\n";
pg_free_result($result);
pg_close($dbconn);
?>
33
pg_fetch_assoc () pg_fetch_assoc (resource $result [, int $row]): array
Purpose: returns an associative array that corresponds to the fetched
row (records).
pg_fetch_row () pg_fetch_row (resource $result [, int $row]): array
Purpose: fetches one row of data from the result associated with the
specified result resource.
Apart from these there are various other functions also supported/provided.
Exercises
34
b. Accept project name from the user. Write a PHP script which will display
all employees working on that project along with number of hours they
worked on it.
An insurance agent sells policies to clients. Each policy is of a particular type like vehicle
insurance, life insurance, accident insurance etc, and there can be many policies of a
particular type. Each policy will have many monthly premiums, and each premium is
associated to only one policy. Assume appropriate attributes for agents, policy,
premiums, policy-types.
The following constraints have to be defined on the relations.
a. The policy types can be only accident, life, vehicle.
b. The agents can be only from Pune, Mumbai, Chennai.
c. The policy amount should be greater than 20000.
d. The policy-sale-date should be greater than the policy-intro-date.
Using database created for the above case-study, solve the following.
*Use appropriate error message if input entered by the user is incorrect. *
Write a PHP Script for –
1. Accept minimum years of experience from the user. Display agent details such as
name, city he belongs to and experience in tabular format who are having at-least
that much experience.
2. Accept agent name from the user. Display all policy holders those who have
bought policies from that agent.
3. Accept details of new agent and add that record into database.
35
OR
1. Accept policy type from the user using radio button. Display all policy holders
along with details such as name, birthdate in the tabular format who have bought
policies of that type.
2. Accept policy amount from the user. Display count of policies with at-least that
amount.
3. Accept details of policy number and remove that record from the database.
OR
Assignment Evaluation
0: Not Done [ ] 1: Incomplete [] 2: Late Complete []
36
Assignment Number 6 : XML and AJAX
Pre-requisite:
Demonstration of XML and AJAX concepts with their syntax using simple
programmes
Students must read theory and syntax for solving programmes before his/her
practical slot.
Solve SET A, B or C assigned by instructor in allocated slots only.
Theory:
37
<phone>274850503</phone>
<contact-info>
Document Prolog Section :
Document Prolog comes at the top of the document, before the root element. This section
contains −
XML declaration
Document type declaration
Document Elements Section:
Document Elements are the building blocks of XML. These divide the document into a
hierarchy of sections, each serving a specific purpose.
XML declaration :
It contains details that prepare an XML processor to parse the XML document. It is
optional, but when used, it must appear in the first line of the XML document.
<?xml version="version_number" encoding="encoding_declaration"
standalone="standalone_status" ?>
An XML declaration should abide with the following rules:
The XML declaration is case sensitive and must begin with "<?xml>" where
"xml" is written in lower-case. If the XML declaration is included, it must contain
version number attribute.
The Parameter names and values are case-sensitive.The names are always in
lower case.
The order of placing the parameters is important. The correct order is:version,
encoding and standalone. Either single or double quotes may be used.
The XML declaration has no closing tag i.e. </?xml>
38
For example,
<Message>This is incorrect</message>
<message>This is correct</message>
XML Elements :
• An XML file is structured by several XML-elements, also called XML-nodes or XML-
tags.
XML-elements' names are enclosed by triangular brackets <> .
• Each XML-element needs to be closed either with start or with end elements as shown
below:
<element>....</element>.
• An XML document can have only one root element
• An XML-element can contain multiple XML-elements as its children, but the children
elements must not overlap.
• In XML, all elements must be properly nested within each other.
XML attributes:
• An XML-element can have one or more attributes.
• Attribute names in XML (unlike HTML) are case sensitive. That is, HREF andhref are
considered two different XML attributes.
• Same attribute cannot have two values in a syntax
So XML follows tree structure
<root>
<child>
<subchild>.....</subchild>
</child>
</root>
39
• To create root element of xml document, first create object of SimpleXMLElement
class and
initialize with root element.
• For example :
• $bk=new SimpleXMLElement(“<bookstore/>”);
40
children of a
specified node.
simplexml_l Converts an simplexml_load_file $xml=simplexml_load_file("no
oad XML (file) te.xml"
_file() file into a );
SimpleXMLEle
ment object
simplexml_l The simplexml_load <?php
oad simplexml_load _string() $note=<<<XML
_string() _str <note>
ing() function <to>Tove</to>
converts a </note>
wellformed XML;
XML string $xml=simplexml_load_string($
into a note);
SimpleXMLEle
me
nt object.
41
</bookstore>
// book.php
<?php
$xml = simplexml_load_file("book.xml");
echo $xml->getName() . "<br />";
foreach($xml->children() as $child)
{
echo $child->getName() . "<br>";
foreach($child->attributes() as $k=>$v)
{
echo $k . "=". $v . "<br>";
foreach($child->children() as $i=>$j)
{
echo $i .":". $j."<br>";
}
}
}
?>
Exercises
1. Create a XML file which gives details of students admitted for different courses
in Your College.
Course names can be
42
A) Arts
B) Science
C) Commerce
D) Management
Elements in each course are in following format.
<Course>
<Level>…</Level>
<Intake Capacity>…</Intake Capacity>
</Course>
Save the file with “Course.xml”
2. Write PHP script to generate an XML code in the following format
<?xml version=1.0”?>
<ABC College>
<Computer Application Department>
<Course> BCA(Science) </Course>
<Student Strength > 80</Student Strength>
<Number of Teachers>12</Number of Teachers>
</ABC College>
</Computer Application Department>
43
3: Needs Improvement [] 4: Complete [] 5: WellDone []
AJAX is a technique for creating fast and dynamic web pages. AJAX allows web
pages to be updated asynchronously by exchanging small amounts of data with the server
behind the scenes.This menas that it is possible to update parts of a web page,without
reloading the whole page.
Update a web page without reloading the page
Request data from a server-after the page has loaded
Receive data from a server-after the page has loaded
Send data to a server-in the background
All modern browsers (IE7+, Firefox, Chrome, Safari, and Opera) have a built in
XMLHttpRequest object.
ob = new XMLHttpRequest();
44
Property Description
onreadystatechange Defines a function to be called when the readyState
property changes.
readyState Holds the status of the XMLHttpRequest.
0 : request not initialized
1 : server connection established
2 : request received
3 : processing request
4 : request finished and response is ready
responseText Returns the response data as a string
responseXML Returns the response data as XML data
Status Returns the status-number of a request
200 : OK
403 : forbidden
404 : Not Found
statusText Returns the status-text(e.g. “OK” or ”Not Found”)
Exercises
1. Write AJAX program to read a text file and print the contents of the file when the
user clicks on the Print button.
2. Write a AJAX program to search Student name according to the character typed
and display list using array
3. Write a AJAX program to read contact. dat file and print the contain of a file in a
tabular form when the user clicks on print button.
contact.dat file contain srno, name, residence_number, mobile_number, context/
relation.
45
[ Enter at least 3 record in contact.dat file]
2. Write AJAX program to print movie by selecting an actor’s name. create table
Movie and Actor with 1:M cardinality as follows:
Movie ( mno, mname, release_year)
Actor( ano, aname)
Assignment Evaluation
0: Not Done [ ] 1: Incomplete [] 2: Late Complete []
46