Web Technologies Units 1 2
Web Technologies Units 1 2
Introduction to PHP: Declaring variables, data types, arrays, strings, For Micro Notes by the
operators, expressions, control structures, functions, Reading data from web Students…………..
form controls like text boxes, radio buttons, lists etc., Handling File Uploads.
Connecting to database (MySQL as reference), executing simple queries,
handling results, Handling sessions and cookies
Introduction
PHP is a server-side scripting language. PHP processor is open source and can
be downloaded without any cost. PHP was developed by Rasmus Lerdorf, a
member of the Apache Group, in 1994. Most of the binaries were written in C.
Lerdorf called the initial PHP as Personal Home Page. But later it was changed
to Hypertext PreProcessor.
What is PHP? What are the common uses of PHP? (2 marks May
2017)
PHP stands for “PHP: Hypertext Preprocessor”. Earlier it was called Personal
Home Page.PHP is a server side scripting language that is embedded in HTML.
The default file extension for PHP files is ".php".PHP supports all the databases
that are present in the market.PHP applications are platform independent. PHP
application developed in one OS can be easily executed in other OS also.
ACE Engineering College: Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
2 Web Technologies
After a web server is installed, place the PHP file hello.php in the web server's
root directory and start the web server. Now, open a web browser like chrome,
firefox or internet explorer and type the following URL in the address bar:
http://localhost/hello.php or
http://localhost:80/hello.php
80 is the port at which the web server listens for incoming HTTP requests. The
output of the PHP script is:
ACE Engineering College: Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
3 Personal Home Page (PHP)
<h1> Using PHP and HTML together</h1> //Contain <h1> header and some
text
Here is PHP info: </br></br>
<?php // <?php starts a PHP section
phpinfo(); //PHP function phpinfo(); displays information
about the PHP //installation, Every PHP
statement ends with semicolon
?>
</body>
</html>
When this page is run by PHP engine on the server HTML will be passed
through browser and PHP part will be executed
ACE Engineering College: Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
4 Web Technologies
Example:
Using the format value %f:
<?php
$number = 123;
printf("%f",$number);
?>
Example 2
<?php
$number = 9; $str = "Beijing";
printf("There are %u million bicycles in %s.",$number,$str);
?>
Adding comments to PHP code
// This is single-line comment
# This is also a single-line comment
/*
This is a multiple-lines comment block
that spans over multiple
lines
*/
<?php
$name="ACE";
$age = 21;
$price = 2.55;
$number = -2;
?>
After the execution of the statements above, the variable $name will hold the
value ACE, the variable $age will hold the value 21, the variable $price will
hold the value 2.55, and the variable $number will hold the value -2.
Creating Variables
Variables are "containers" that are used for storing information.
In PHP, a variable starts with the $ sign, followed by the name of the variable.
Creating constants
Constants are identifiers which are used to store values that cannot be changed
once initialized. A constant doesn't begin with a dollar ($) sign. The convention
for constants is, the name of a constant should always be written in uppercase.
We use the function define to create constants. Below example demonstrates
creating and using constants in PHP:
ACE Engineering College: Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
6 Web Technologies
<?php
define("PI", 3.142); print(PI);
$area = PI*10*10; //Let radius be 10 print("<br />Area of circle is: $area");
?>
Data Types
PHP provides four scalar types namely Boolean, integer, double and string
and two compound types namely array and object and two special types namely
resource and NULL.
PHP has a single integer type, named integer. This type is same as long type
in C. The size of an integer type is generally the size of word in the machine. In
most of the machines that size will be 32 bits.
PHP's double type corresponds to the double type in C and its successors.
Double literals can contain a decimal point, an exponent or both. An exponent
is represented using E or e followed by a signed integer literal. Digits before
and after the decimal point are optional. So, both .12 and 12. are valid double
literals.
The only two possible values for a Boolean type are TRUE and FALSE both of
which are case-insensitive. Integer value 0 is equal to Boolean FALSE and
anything other than 0 is
equal to TRUE. An empty string and string "0" are equal to Boolean FALSE
and remaining other strings are equal to TRUE. Only double value equal to
Boolean FALSE is 0.0.
ACE Engineering College: Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
7 Personal Home Page (PHP)
Assignment Description
x=y Assigning value of y to x
x += y Adding x and y and store the result in x
x -= y Subtracting y from x and store the result in x
x *= y Multiplying x and y and store the result in x
x /= y Dividing x by y and store the quotient in x
x %= y Dividing x by y and store the remainder in x
Example: To check how many minutes someone has been in the pool- if its
more than 30minute, it's time to get out.
<html>
<head>
ACE Engineering College: Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
9 Personal Home Page (PHP)
<?php
$minutes=31;
if($minutes > 30)
{
echo "Wer time is UP!!<br>";
echo "Please get out of the pool.";
}
?>
</body>
</html>
else
{
echo "Nice weather outside";
}
?>
</body></html>
if (condition1) {
code to be executed when condition1 is true;
} elseif (condition2) {
code to be executed when condition2 is true;
} else {
code to be executed when conditions are false;
}
<html>
<head>
<title> Using the elseif statement</title>
</head>
<body>
<h1>Using the elseif Statement</h1>
<?php
$a=40;
$b=30;
if ($a > $b)
{
echo "$a is bigger than $b";
} elseif ($a == $b)
{
echo "$a is equal to $b";
} else {
echo "$a is smaller than $b";
}
ACE Engineering College: Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
11 Personal Home Page (PHP)
?>
</body>
</html>
If the if statement's conditional expression is false, It will check the first elseif
statements expression, if it’s true elseif code is executed and if its false it
moves to the next elseif statement and so on. At he end else statement is
executed if the no other code is executed in the if statement up to this point.
switch statement:
switch statement lets us replace long if-elseif-else ladder of condition
checking with switch statement. switch statement compares a value against
case statement and execute a code block whose value matches the case value. if
no case value matches the value, default statement is executed. break statement
ends execution of the switch statement, if we don't write break statement,
execution will continue with the code.
<?php
switch(value){
case value1:
// code block 1
break;
case value2:
// code block 2
break;
default:
// default code block
break;
}
Example:
<html>
<head>
<title> Using the switch statement</title>
</head>
<body>
<h1>Using the switch Statement</h1>
<?php
ACE Engineering College: Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
12 Web Technologies
$favcolor = "red";
switch ($favcolor)
{
case "red":
echo "Wer favorite color is red!";
break;
case "blue":
echo "Wer favorite color is blue!";
break;
case "green":
echo "Wer favorite color is green!";
break;
default:
echo "Wer favorite color is neither red, blue, nor green!";
}
?>
</body>
</html>
for loop
for loop is a repetition control structure that allows us to execute a block of
code a specified number of times.
When we want to execute same block of code over and over again specified
number of times.
Syntax:
for( expression1 ; expression1 ; expression1 )
statement
First, for loop executes expression1; then it checks the value of expression2 - if
true , loop executes statement once.
Then it executes expression3 and after that checks the expression2 again-- if
true loop execute statement once again.
Then loop executes expression3 again, and keeps going untill expression2
becomes false.
ACE Engineering College: Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
13 Personal Home Page (PHP)
<html>
<head>
<title>
Using the for loop
</title>
</head>
<body>
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
</body>
</html>
for loop can handle multiple loop counters by seperating them with comma
operator.
<?php
for ($i=2, $k=2; $i<6 && $k<6 ; $i++, $k++) {
echo "$i * $k = ",$i *$k,"<br>";
}
?>
We can put one loop inside a another loop, call as nested loop.
<?php
for ($row = 1; $row <= 5; $row++)
{
for ($col = 1; $col <= 5; $col++)
{
echo '*';
}
echo "\n";
}
?>
ACE Engineering College: Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
14 Web Technologies
Outputs:
*****
*****
*****
*****
*****
While Loop
When we want to execute same block of code over and over again as long as
the condition is true, we go for while loop.
Syntax:
while (expression)
{
statement
}
While expression is true, the loop executes statement. When expression is false,
the loop ends.
<html>
<head>
<title>
Using the while loop
</title>
</head>
<body>
<h1> Using the while loop </h1>
<?php
$x=1;
while($x<10)
{
echo "Now \$x holds : ",$x,"<br>";
$x++;
}
?>
</body>
</html>
ACE Engineering College: Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
15 Personal Home Page (PHP)
Example:
<html>
<head>
<title>
Using the do...while loop
</title>
</head>
<body>
<h1> Using the do...while loop </h1>
<?php
$x=1;
do
{
echo "Now \$x holds : ",$x,"<br>";
$x++;
} while($x<10);
?>
</body>
</html>
ACE Engineering College: Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
16 Web Technologies
<html>
<head>
<title> Using the break statement</title>
</head>
<body>
<h1> Using the break statement</h1>
<?php
for ( $x=0 ; $x < 100 ; $x++)
{
echo "I 'm going to do this hundred times!<br>";
if ($x == 10)
{
echo "Alright, i'm quitting,<br>";
}
}
?>
</body>
</html>
ACE Engineering College: Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
17 Personal Home Page (PHP)
continue is used within looping structures to skip the rest of the current loop
iteration and continue execution at the condition evaluation and proceed to the
beginning of the next iteration.
break ends a loop completely, continue just shortcuts the current iteration and
moves on to the next iteration.
<html>
<head>
<title>Using the continue statement</title>
</head>
<body>
<?php
$x=1;
for( $x=-2; $x < 3 ; $x++ )
{
if ($x == 0)
{
continue;
}
Arrays
Array is a collection of heterogeneous elements. There are two types of arrays
in PHP. First type of array is a normal one that contains integer keys (indexes)
which can be found in any typical programming languages. The second type of
arrays is an associative array, where the keys are strings.
Array Creation
Arrays in PHP are dynamic. There is no need to specify the size of an array. A
normal array can be created by using the integer index and the assignment
operator as shown below:
$array1[0] = 10;
If no integer index is specified, the index will be set to 1 larger than the
previous largest index value used. Consider the following example:
$array2[3] = 5;
$array2[ ] = 90;
In the above example, 90 will be stored at index location 4.
There is another way for creating an array, using the array construct, which is
not a function. The data elements are passed to the array construct as shown in
the below example:
$array3 = array(10, 15, 34, 56);
$array4 = array( );
In the above example array4 is an empty array which can be used later to store
elements. A traditional array with irregular indexes can be created as shown
below:
$array5 = array(3 => 15, 4 =>, 37, 5 => 23);
The above code creates an array with indexes 3, 4 and 5.
<html>
<head>
<title>Using a for loop to loop over an Array</title>
</head>
<body>
<h1>Using a for loop to loop over an Array</h1>
</br></br><?php
$cities=array("Hyderabad","Chennai","Delhi","Mumbai","Pune","Kolk
ata","Lucknow","Chandigarh");
$arrayLength=count($cities);
for($i=0; $i<$arrayLength;$i++)
{
echo $cities[$i],"<br>";
}
?>
</body>
</html>
ACE Engineering College: Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
20 Web Technologies
<?php
$cities=array("Hyderabad","Chennai","Delhi","Mumbai","Pune","Kolk
ata","Lucknow","Chandigarh");
print_r($cities);
?>
when foreach starts executing, the array pointer is automatically set to the first
element of the array. On each iteration, the value of the current element is
assigned to $value and the array pointer is incremented by one.
The second form of foreach loop lets us to work with keys as well as values.
Element is a combination of element key and element value. PHP also support
slightly different type of array in which index numbers are replaced with user
defined string keys.
This type of array is known as Associative Array. The keys of the array must be
unique, each key references a single value. The key value relationship is
expressed through => symbol.
For example:
<html>
<head>
<title>Using a foreach loop with keys and values in an Array
</title>
</head>
<body>
<h1>Using a foreach loop with keys and values in n Array</h1></br></br>
<?php
$details=array("name"=>"ACE","Type"=>"College","Place"=>"Hydera
bad");
foreach ($cities as $key=>$value)
{
echo "$key : $value<br>";
}
?></body></html>
Note: If we don’t provide an explicit key to an array element, The new key
value depends upon the previous key.
<?php
$a=array(10,100=”ACE”,30); //[0]=>10 [100]=>ACE [101]=30
print_r($a);
?>
<?php
$a=array(10,20,0=>30);
print_r($a); //[0]=30 [1]=20
?>
ACE Engineering College: Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
22 Web Technologies
To handle multiple-item return value from the each function, we can use list()
function . Example:
<?php
$Language=array("PHP","XML","Servlet","JSP","JavaScript");
list($x, $y, $z)=$Language;
echo "We have covered $x, $y and $z.";
?>
list() function assign the two return value from each separate variable. Like:
<html>
<head>
<title>Using a while loop with keys and values in an Array</title></head>
<body>
<h1>Using a while loop with keys and values in n Array</h1></br></br>
<?php
$details=array("name"=>"ACE","Type"=>"College","Place"=>"Hydera
bad");
while (list($key, $value)=each($details))
{
echo "$key : $value<br";
}
?>
</body>
</html>
<?php
$ice_cream[0]="Chocolate";
$ice_cream[1]="Mango";
$ice_cream[2]="Strawberry";
$text=implode(" , ", $ice_cream); //Outputs: Chocolate, Mango,
Strawberry
?>
<?php
$ice_cream="Chocolate, Mango, Orange";
$ice_cream=explode(" , ", $text);
print_r($ice_cream); //Outputs: Array( [0]=>Chocolate [1]=>Mango
[2]=>Strawberry)
?>
ACE Engineering College: Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
24 Web Technologies
Functions
Now that we should have learned about variables, loops, and conditional
statements it is time to learn about functions.
When we have a block of code that needs to be run multiple times in our
application, we put that block of code into a function.
A function is a block of code (that performs a task) that can be executed
whenever we need it.
Advantages of using functions is, it reduces the repetition of code within a
program.
<?php
function display() {
echo "Hello world!";
}
display(); // call the function
?>
ACE Engineering College: Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
25 Personal Home Page (PHP)
function functionName([parameter_list...])
{
[statements];
}
Example:If we want to pass the person's name, and our function will
concatenate this name onto a greeting string.
<html>
<head><title> Passing data to functions</title></head>
<body>
<?php
function display($name) {
echo "Hello $name !!";
}
display("Aditya"); // call the function
?>
</body>
</html>
Example:
Define a function to find total of student's test scores and displays the total.
<html>
<head>
<title> Passing arrays to function </title>
</head>
<body>
<h1> Passing arrays to function </h1>
<?php
$scores=array(90,40,65,98,75); //First create an array of test score
//Now, Lets define an total function:
function total($array)
{
$totalmarks=0;
foreach($array as $value) //we use foreach statement to loop over
the array
ACE Engineering College: Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
26 Web Technologies
{
$totalmarks + = $value ;
}
}
echo " The total marks: ",total($scores); //Call the function: total($scores)
?>
</body>
</html>
Example:
<html>
<head>
<title>Handling Local and Global scope in functions</title>
</head>
<body>
<h1>Handling Local and Global scope in functions</h1>
<?php
$value = 4;
ACE Engineering College: Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
27 Personal Home Page (PHP)
function func1()
{
$value = 80000;
echo "Inside function one \$value : ",$value,"<br";
}
function func2()
{
global $value;
echo "Inside function two \$value : ",$value,"<br";
}
?>
</body>
</html>
<html>
<head>
<title>Keeping a Count of function call</title>
</head>
<body>
<h1>Keeping a Count of function call</h1>
<?php
echo "Now the count is: ". count_function(),"<br>"; //Now the count is:1
echo "Now the count is: ". count_function(),"<br>"; //Now the count is:1
echo "Now the count is: ". count_function(),"<br>"; //Now the count is:1
echo "Now the count is: ". count_function(),"<br>"; //Now the count is:1
ACE Engineering College: Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
28 Web Technologies
function count_function()
{
$counter = 0;
$counter++;
return $counter;
}
?>
</body>
</html>
Above code will print counter value always 1, because $counter is reset to 0
every time we call the cunt_function.
function count_function()
{
global $counter;
$counter++;
return $counter;
}
?>
Connecting to Database:
PHP have Built-in Database Access.
PHP provides built-in database connectivity for a wide range of databases –
MySQL, PostgreSQL, Oracle, Berkeley DB, Informix,
mSQL, Lotus Notes, and more.
ACE Engineering College: Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
29 Personal Home Page (PHP)
What is MySQL?
MySQL is a database. The data in MySQL is stored in database objects called
tables.
A table is a collection of related data entries and it consists of columns and
rows.
Databases are useful when storing information categorically. A company may
have a database with the following tables: "Employees", "Products",
"Customers" and "Orders".
Database Tables
A database most often contains one or more tables. Each table is identified by a
name (e.g. "Customers" or "Orders"). Tables contain records (rows) with data.
<?php
$con = mysql_connect("localhost","peter","abc123"); ]
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// some code
?>
Closing a Connection
The connection will be closed automatically when the script ends. To close the
connection before, use the mysql_close() function:
ACE Engineering College: Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
30 Web Technologies
<?php
$con = mysql_connect("localhost","peter","abc123"); if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// some code mysql_close($con);
?>
Create a Database
The CREATE DATABASE statement is used to create a database in MySQL.
Syntax
CREATE DATABASE database_name
To get PHP to execute the statement above we must use the mysql_query()
function. This function is used to send a query or command to a MySQL
connection.
Example
The following example creates a database called "my_db":
<?php
$con = mysql_connect("localhost","peter","abc123");
// connect to database if (!$con)
{
die('Could not connect: ' . mysql_error());
} // exit script
if (mysql_query("CREATE DATABASE my_db",$con))
// create database my_db
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}
mysql_close($con); // close db connection
?>
ACE Engineering College: Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
31 Personal Home Page (PHP)
Create a Table
The CREATE TABLE statement is used to create a table in MySQL.
Syntax
CREATE TABLE table_name (
column_name1 data_type, column_name2 data_type, column_name3
data_type,
....
)
We must add the CREATE TABLE statement to the mysql_query() function to
execute the command.
Example
The following example creates a table named "Persons", with three columns.
The column names will be "FirstName", "LastName" and "Age":
<?php
$con = mysql_connect("localhost","peter","abc123"); if (!$con)
{
die('Could not connect: ' . mysql_error()); }
// Create database
if (mysql_query("CREATE DATABASE my_db",$con))
{
echo "Database created"; } else
{
echo "Error creating database: " . mysql_error(); }
// Create table mysql_select_db("my_db", $con);
$sql = "CREATE TABLE Persons (
FirstName varchar(15), LastName varchar(15), Age int)";
// Execute query mysql_query($sql,$con);
mysql_close($con);
?>
The second form specifies both the column names and the values to be inserted:
INSERT INTO table_name (column1, column2, column3,...) VALUES
(value1, value2, value3,...)
To get PHP to execute the statements above we must use the mysql_query()
function. This function is used to send a query or command to a MySQL
connection.
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
mysql_close($con);
?>
Syntax
SELECT column_name(s) FROM table_name
ACE Engineering College: Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
33 Personal Home Page (PHP)
To get PHP to execute the statement above we must use the mysql_query()
function. This function is used to send a query or command to a MySQL
connection.
Example
The following example selects all the data stored in the "Persons" table (The *
character selects all the data in the table):
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT * FROM Persons");
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName']; echo "<br />";
}
mysql_close($con);?>
ACE Engineering College: Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
34 Web Technologies
Destroying a Session
If we wish to delete some session data, we can use the unset() or the
session_destroy() function.
The unset() function is used to free the specified session variable:
<?php
unset($_SESSION['views']);
?>
We can also completely destroy the session by calling the session_destroy()
function.
PHP 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, we can both create and retrieve cookie values.
ACE Engineering College: Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
35 Personal Home Page (PHP)
In the example below, we will create a cookie named "user" and assign the
value "Alex Porter" to it. We also specify that the cookie should expire after
one hour:
<?php
setcookie("user", "Alex Porter", time()+3600);
?>
In the example below, we retrieve the value of the cookie named "user" and
display it on a page:
<?php
// Print a cookie
echo $_COOKIE["user"];
// A way to view all cookies print_r($_COOKIE);
?>
In the following example we use the isset() function to find out if a cookie has
been set:
<html>
<body>
<?php
if (isset($_COOKIE["user"]))
echo "Welcome " . $_COOKIE["user"] . "!<br />"; else
echo "Welcome guest!<br />";
?>
</body>
</html>
To Delete a Cookie?
When deleting a cookie we should assure that the expiration date is in the past.
<?php
// set the expiration date to one hour ago setcookie("user", "", time()‐3600);
?>
ACE Engineering College: Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
36 Web Technologies
If fopen is unable to open the file, it returns 0. This can be used to exit the
function with an appropriate message.
File Modes
The following table shows the different modes the file may be opened in.
Mode Description
r Read Only mode, with the file pointer at the start of the file.
r+ Read/Write mode, with the file pointer at the start of the file.
w Write Only mode. Truncates the file (effectively overwriting it).
If the file doesn't exist, fopen will attempt to create the file.
w+ Read/Write mode. Truncates the file (effectively overwriting it).
If the file doesn't exist, fopen will attempt to create the file.
a Append mode, with the file pointer at the end of the file. If the
file doesn't exist, fopen will attempt to create the file.
a+ Read/Append, with the file pointer at the end of the file. If the
file doesn't exist, fopen will attempt to create the file.
Note: The mode may also contain the letter 'b'. This is useful only on systems
which differentiate between binary and text files (i.e. Windows. It's useless on
Unix/Linux). If not needed, it will be ignored.
Closing a File
The fclose function is used to close a file when we are finished with it.
fclose($fp);
ACE Engineering College: Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
37 Personal Home Page (PHP)
Reading:
Reading from Files
We can read from files opened in r, r+, w+, and a+ mode. The feof function is
used to determine if the end of file is true.
if ( feof($fp) )
echo "End of file<br>";
The feof function can be used in a while loop, to read from the file until the end
of file is encountered. A line at a time can be read with the fgets function:
while( !feof($fp) ) {
// Reads one line at a time, up to 254 characters. Each line ends with a
newline.
$myline = fgets($fp, 255);
echo $myline;
}
We can read in a single character at a time from a file using the fgetc function:
while ( !feof($fp) ) {
// Reads one character at a time from the file. $ch = fgetc($fp);
echo $ch;
}
We can also read a single word at a time from a file using the fscanf function.
The function takes a variable number of parameters, but the first two
parameters are mandatory. The first parameter is the file handle, the second
parameter is a C-style format string. Any parameters passed after this are
optional, but if used will contain the values of the format string.
$listFile = "list.txt"; // See next page for file contents if (!($fp = fopen($listFile,
"r")))
exit("Unable to open $listFile.");
while (!feof($fp)) {
// Assign variables to optional arguments
$buffer = fscanf($fp, "%s %s %d", $name, $title, $age);
if ($buffer == 3) // $buffer contains the number of items it was able to
assign print "$name $title $age<br>\n";
}
ACE Engineering College: Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
38 Web Technologies
We can also store the variables in an array by omitting the optional parameters
in fscanf:
while (!feof($fp)) {
$buffer = fscanf($fp, "%s %s %d"); // Assign variables to an array
// Use the list function to move the variables from the array into
variables list($name, $title, $age) = $buffer;
print "$name $title $age<br>\n";
}
We can read in an entire file with the fread function. It reads a number of bytes
from a file, up to the end of the file (whichever comes first). The filesize
function returns the size of the file in bytes, and can be used with the fread
function, as in the following example.
$listFile = "myfile.txt";
if (!($fp = fopen($listFile, "r")))
exit("Unable to open the input file, $listFile.");
$buffer = fread($fp, filesize($listFile));
echo "$buffer<br>\n";
fclose($fp);
We can also use the file function to read the entire contents of a file into an
array instead of opening the file with fopen:
$array = file(‘filename.txt’);
Each array element contains one line from the file, where each line is
terminated by a newline.
Writing to Files
The fwrite function is used to write a string, or part of a string to a file. The
function takes three parameters, the file handle, the string to write, and the
number of bytes to write. If the number of bytes is omitted, the whole string is
written to the file. If we want the lines to appear on separate lines in the file,
use the \n character. Note: Windows requires a carriage return character as well
as a new line character, so if we're using Windows, terminate the string with
\r\n. The following example logs the visitor to a file, then displays all the
entries in the file.
ACE Engineering College: Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
39 Personal Home Page (PHP)
<?php
$logFile = "stats.txt";
$fp = fopen($logFile, "a+"); // Open the file in append/read mode
$userDetails = $_SERVER[‘HTTP_USER_AGENT’]; // Create a string
containing user details if (isset($_SERVER[‘HTTP_REFERER’]))
$userDetails .= " {$_SERVER[‘HTTP_REFERER’]}<br>\r\n"; else
$userDetails .= "<br>\r\n";
fwrite($fp, "$userDetails"); // Write the user details to the file rewind($fp);
// Move the file pointer to the start of the file $entries = 0;
while(!feof($fp)) { // Display each line in the file
$buffer = fgets($fp, 1024);
if ($buffer != "") {
echo $buffer;
$entries++;
}
} // Show a summary
echo "There are $entries entries in the log file<br>"; fclose ($fp);
?>
OBJECTIVEQUESTIONS
02. A PHP script should start with ___ and end with ___:
(A) < php > (B) < ? php ?>
(C) <? ?> (D) <?php ?>
02. Answer: (C) or (D)
ACE Engineering College: Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
40 Web Technologies
track();
track();
?>
(A) 123 (B) 111 (C) 000 (D) 011
06. Answer: (A)
08. Which one of the following functions can be used to compress a string?
(A) zip compress() (B) zip()
(C) compress() (D) gzcompress()
08. Answer: (D)
09. Which one of the following PHP function is used to determine a file’s
last access time?
(A) fileltime() (B) filectime()
(C) fileatime() (D) filetime()
09. Answer: C
10. Which directive determines whether PHP scripts on the server can
accept file uploads?
(A) file_uploads (B) file_upload
(C) file_input (D) file_intake
10. Answer: A
ACE Engineering College: Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
42 Web Technologies
12. Which one of the following databases has PHP supported almost since
the beginning?
(A) Oracle Database (B) SQL
(C) SQL+ (D) MySQL
12. Answer: (D)
13. Which one of the following statements can be used to select the
database
(A) $mysqli=select_db(‘databasename’);
(B) mysqli=select_db(‘databasename’);
(C) mysqli->select_db(‘databasename’);
(D) $mysqli->select_db(‘databasename’);
13. Answer: D
14. Which one of the following methods can be used diagnose and
displayinformation about a MySQL connection error?
(A) connect_errno() (B) connect_error()
(C) mysqli_connect_errno() (D) mysqli_connect_error()
14. Answer: (C)
14. Which one of the following is the very first task executed by a session
enabled page?
(A) Delete the previous session
(B) Start a new session
(C) Check whether a valid session exists
(D) Handle the session
14. Answer: C
ACE Engineering College: Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
43 Personal Home Page (PHP)
17. Which one of the following function is capable of reading a file into a
string variable?
(A) file_contents() (B) file_get_contents()
(C) file_content() (D) file_get_content()
17. Answer: (B)
18. Which one of the following methods is responsible for sending the
query to the database?
(A) query() (B) send_query()
(C) sendquery() (D) query_send()
18. Answer: (A)
19. Which one of the following method is used to retrieve the number of
rows affected by an INSERT, UPDATE, or DELETE query?
(A) num_rows() (B) affected_rows()
(C) changed_rows() (D) new_rows()
19. Answer: (B)
20. Which of the following methods is used to execute the statement after
the parameters have been bound?
(A) bind_param() (B) bind_result()
(C) bound_param() (D) bound_result()
20. Answer: (A)
ACE Engineering College: Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
44 Web Technologies
09. Discuss associative arrays with example What is the output of following:
10. <?php
$x=10;
function f()
{
echo GLOBALS[‘$x’];
}
f();
echo $x;
?>
ACE Engineering College: Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
45 Personal Home Page (PHP)
01. What is string Interpolation? Explain briefly about PHP’s Internal Data
Types
02. Explain the conversion between different data types in PHP with an
Example program.
03. How text manipulation is done in PHP. Write a program to compare two
strings and print respectively.
07. Write a PHP program to count number of words in the given string.
08. Write a PHP program to check whether given number is Armstrong or not.
01. Write a php program that replaces some characters with some other
characters in a string.
ACE Engineering College: Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
46 Web Technologies
01. How to set a page as a home page in a php based site? How to find the
length of a string?
02. What is mean by an associative array? Write a program to print the name
and the age of a person’s using associative arrays.
01. How to set a page as a home page in a php based site? How to find the
length of a string?
02. What is mean by an associative array? Write a program to print the name
and the age of a person’s using associative arrays.
ACE Engineering College: Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
Chapter
2 XML
Introduction to XML
XML means eXtensible Markup Language. XML was developed by an
organization called the World Wide Web Consortium (W3C) and is available as
an open standard.
Markup is a set of instructions, often called tags. XML allows we to create our
own self-descriptive tags and use them in XML document to satisfy application
requirement. XML tags are not predefined like HTML tags. HTML supports a
predefined set of tags and HTML document can use only those tags.
Since more such new tags may be defined , XML is said to be extensible.
We can create XML document using text editor and save it with “.xml”
extension.
XML is derived from Standard Generalized Markup Language (SGML), which
is a system for defining the markup Language.
Role Of XML
XML plays a significant role in web development. XML document separates the
content from their presentation. It does not specify how the content should be
displayed. It only specifies the contents with their logical structure. The
formatting task is done on an external style sheet; the look and feel may be
changed very easily by choosing different style sheets.
XML also promotes easy data sharing among applications. Since application
hold data in different structures, XML help us in mapping data from one to
another. Each data structure is mapped to an agreed-upon XML structure. This
XML structure may then be used by other applications. So, each application has
to deal with only two structures: its own and the XML structure.
ACE Engineering College: Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
72 Web Technologies
Prolog
This part of the XML document contain the following parts:
• XML Declaration
• Optional Processing Instruction
• Comments
• Document Type Declaration
XML Declaration
Every XML document start with a one-line XML declaration. This declaration
must be always the first statement in wer XML document.
<?xml version=”1.0” ?>
This declaration describes the document itself. This declaration is a instruction
that tells the processing agent that the document is an XML document. The
mandatory version attributes indicates the version used in the document.XML
Declaration may use two optional attributes: encoding & standalone.
Processing Instruction
Processing instructions start with <? and end with ?>. The XML Declaration
discussed above is a processing instruction.
Comments
Comments are used to describe what our program/ Block of code is going to do.
Comments are ignored by XML parsers and applications using the XML
document. An XML comments start with <!- -and ends with - ->
<!- -comment text- ->
The following point should be remembered while using the comments:
• Do not use double hyphen ‘ - -‘
• Never place comments within a tag.
• Never place a comment before the XML Declaration.
DTD file holds the rules of grammar for a particular XML data structure. Those
rules are used by the validating parser to check that is not only the valid XML
file, but it also obeys its own internal rules.
Body
Body portion of the XML document contains textual data marked up by tags. It
must have one element, called the document element or root element. Consider
the following XML Document:
<?xml version="1.0" encoding="UTF-8"?>
<greeting>Hello World!!</greeting>
The name of the root element is <greeting>, which contain the text “Hello
World!!”.
There can be one and only one root element. The following XML document is
not valid as it have two top level elements, <greeting> and <message>
<?xml version="1.0" encoding="UTF-8"?>
<greeting>Hello World!!</greeting>
<message>World is beautiful</message>
The root element contains other elements which, in turn contain other elements:
<?xml version="1.0" encoding="UTF-8"?>
<contact>
<person>
<name>My College</name>
<number>9876543210</number>
</person>
<person>
<name>Wers College</name>
<number>901234567</number>
</person>
</contact>
This XML document has the root element <contact> which has two <person>
elements. Each <person> element has two elements, <name> and <number>
Elements
An XML element consists of starting tag, an ending tag, its contents and
attributes. The content may be simple text, or other elements, or both. XML
elements are used to store data.
ACE Engineering College: Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
74 Web Technologies
The XML tag begins with the lass than character (‘<’) and ends with the greater
than (‘>’) character. Every tag must have the corresponding ending tag. The
ending tag looks exactly like the starting tag except that it includes a slash(‘/’)
character before the tag name. All information in this element must be contained
in the starting and ending tags.
Example:
<greeting> Hello world!! </greeting>
Here, <greeting> is the starting tag and </greeting> is the ending tag. Element
have only text content “Hello World!!”
Attributes
Attributes are used to describe elements or to provide more information about
element. They appear in the starting tag of the element.
Syntax:
<element-name attribute-name="attribute-value">....</element-name>
Example:
<employee gender=”male”>….</employee>
An element can also have multiple attributes:
<employee gender=”male” id=”12345”>….</employee>
Well-Formed XML
An XML document is said to be well-formed if it contains tags and text that
confirms with the basic XML well-formedness constraints.
The following rules must be followed by the XML document to be well-
formed:
An XML document must have one and exactly one root element.
All tags must be closed
Every element must have a closing tag corresponding to its opening tag.
The following code is well formed because the opening tag <name> has its
corresponding closing tag </name>
<name> CSE A-Section</name>
The following document fragment is not well-formed as there is no closing tag
for the opening tag <name>
<name> CSE A-Section
A tag must be closed even if it does not have any content(empty element). In
HTML , some tags such as <img>, <br>, <hr> do not require any closing tag.
But in XML closing tag is always needed.
ACE Engineering College: Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
75 XML
XML provides entities for these special character and XML parser will substitute
each entity by its value.
An entity starts with an '&' character and ends with a ';'.
ACE Engineering College: Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
76 Web Technologies
Valid XML:
Valid XML documents are those that:
• are well formed.
• Comply with rules specified in the DTD or schema
The basic difference between well formed and valid XMl document is that the
former is defined without DTD or schema and the latter requires a DTD or
Schema.
Validation
It is a method of checking whether an XML document is well-formed and
confirms to the rules specified by a DTD or schema. Many tools are available to
validate XML document against DTD or Schema. Linux provide one such
application called xmllint for the validation.
Example-1:
<person sex="male">
<name>Aditya</name>
</person>
Example-2:
<person>
<sex>male</sex>
<name>Anna</name>
</person>
In the first example sex is an attribute. In the second, sex is an element. Both
examples provide the same information.
ACE Engineering College: Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
77 XML
So, When do we use elements and when do we use attributes for presenting our
information?
There are no rules about when to use attributes, and when to use an elements.
Introduction to DTD
Document Type Defination (DTD) is one of several XML Schema Language.
Purpose Of DTD
As we know there are two types of XML document (i) Well-formed (ii)Valid
An XML document is said to be Valid with respect to DTD, if it confirms the
rules specified by a given XML DTD.
• The purpose of DTDs is to provide a framework for validating XML
documents.
• The purpose of a DTD is to define the legal building blocks of an XML
document.
• A DTD defines the document structure with a list of legal elements and
attributes.
• DTD used to specify a content model for each elements and attribute used in
an XML document.
ACE Engineering College: Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
78 Web Technologies
• DTD can’t specify all the constraints that may arise in XML document, But
Large number of constraints can be specified using XML Schema.
PCDATA is the only available text type for simple element declaration.
Example:
<code>
<!CDATA[
<script language="JavaScript">
fucntion less(x, y) {
return x<y;
}
ACE Engineering College: Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
79 XML
a=less(2,3);
</script>
]]>
</code>
in the above example, Everything inside CDATA section is ignored by the
parser.
Example:
<!ELEMENT message (#PCDATA)>
<!ELEMENT title (#PCDATA)>
<!ELEMENT firstName (#PCDATA)>
<!ELEMENT surname (#PCDATA)>
<!ELEMENT dob (#PCDATA)>
Compound Elements
Compound element can contain other elements, an element contain one child
element. Here’s how we can do that:
<!ELEMENT element_name (child_element_name) >
Example:
<!ELEMENT employee (name) >
Above statement indicates the element employee contain another child element
name exactly once. The child element name must be declared separately.
Here is a complete declaration:
<?xml version="1.0"?>
<!DCOTYPE employee [
<!-- 'employee have one child element 'name' -->
<!ELEMENT employee (name)>
<!-- namecontain only text -->
<!ELEMENT name (#PCDATA)>
]>
<employee>
<name> UK Roy</name>
</employee>
ACE Engineering College: Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
80 Web Technologies
Occurrence indicators
Occurrence indicator specifies the number of times an element occurs in a
document.
When no occurrence indicator is specified, the child element must occur exactly
once in an XML document.
Sequence operator [ , ]
The sequence operator ( , ) is used to enforce the ordering of child elements.
The general syntax fo using sequence operator is:
<!ELEMENT parent (expr1, expr2, expr3, …) >
expr1, expr2, expr3… must occur in the document in the order as specified.
Example:
<! ELEMENT employee (firstName, middleName, lastName) >
<!ELEMENT firstName (#PCDATA) >
<!ELEMENT middleName (#PCDATA) >
<!ELEMENT lastName (#PCDATA) >
Choice Operator [ | ]
The choice operator ( | ) is used to select one from among choices separated by
‘|’ symbol.
General Syntax of using choice operator:
<!ELEMENT parent (expr1 | expr2 | expr3 | …) >
expr1 | expr2 | expr3 | … can occur as the child of the element parent.
Example:
<! ELEMENT product (price | discountprice) >
In above declaration, element product can have either price or discountprice as
child.
<! ELEMENT tutorial (name | title | subject) >
Element tutorial can have either a name, a title or a subject but not all
ACE Engineering College: Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
82 Web Technologies
Composite Operator [ () ]
An expression surrounded by parenthesis is treated as single unit (singleton) and
could have any one of the following occurrence indicator : ? , * , or + .
Example:
<! ELEMENT biodata (dob, (company , title) * , contact + ) >
<!ELEMENT dob (#PCDATA) >
<!ELEMENT company (#PCDATA) >
<!ELEMENT title (#PCDATA) >
<!ELEMENT contact (#PCDATA) >
In the above example, company and title form a single unit. The biodata element
can contain Zero or more such units.
ATTRIBUTE DECLARATION
• If an element have attributes, we have to declare the name of the attributes in
DTD.
• An XML attribute is always in the form of a (name, value) pair with element.
• Attributes are useful as it gives more information about an element.
• Attributes declaration is done with ATTLIST declarations.
• A single ATTLIST can declare multiple attributes for a single element type.
• The declaration starts with ATTLIST followed by the name of the element
the attributes are associated with, and the declaration of the individual
attributes.
Syntax
Syntax of Attributes declaration is as follows:
<!ATTLIST element-name attribute-name attribute-type default-value>
where, element-name specifies the name of the element to which the attribute
attribute-name applies.
Example:
<!ELEMENT line EMPTY>
<!ATTLIST line width CDATA '100'>
This specifies the element line has an optional attribute width with value '100', if
attribute is not mentioned.
ACE Engineering College: Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
83 XML
Example:
<! ATTLIST line width CDATA ‘100’>
This declaration says that the attribute width is optional. If the value of this
attribute is specified then the value of this attribute will be the value specified. If
it does not occur, width attribute will get the value 100 from XML processor.
#REQUIRED
This means that the attribute must be specified with a value every time the
element is listed.
#REQUIRED keyword is used to specify that the attribute must be provided.
<! ATTLIST price currency CDATA #REQUIRED> //currency must appear
for price
Example:
<price currency=’INR’>100</price> VALID
<price>100</price> NOT VALID
XML Schemas
The purpose of an XML Schema is to define the legal building blocks of an
XML document. It is used to represent data types of an XML document. It is an
alternative to DTD (Document Type Definition). XML Schema defines
elements, attributes and vales of elements and attributes.
ACE Engineering College: Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
84 Web Technologies
An XML Schema:
• defines elements that can appear in a document
• defines attributes that can appear in a document
• defines which elements are child elements
• defines the order of child elements
• defines the number of child elements
• defines whether an element is empty or can include text
• defines data types for elements and attributes
• defines default and fixed values for elements and attributes
XML markup such as <types> is known as XML schema that conforms to W3C
defined XML schema vocabulary which defines all or part of the vocabulary for
another XML document. The <schema> is the root element for any XML
schema document. The child elements of schema define the data types.
ACE Engineering College: Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
85 XML
The xs qualifier used to identify the schema elements and its types. The
xs:schema is the root element. It takes the attributes xmlns:xs which has the
value, “http://www.w3.org/2001/XMLSchema. This declaration indicates that
the document follows the rule of XMLSchema defined by W3 in year 2001.
The xs:element is used to define the xml element. The Student element is
complexType which has three child elements:name, regno and dept. All these
elements are of simple type string.
Step 2: Write a XML document and reference the xsd file. Named it as
myXML.xml
<?xml version=”1.0”?>
<student xmlns:xsi=”URL”
xsi:schemaLocation=”StudentSchema.xsd”>
<name> Raj </name>
<regno>3212654556</regno>
<dept>CSE</dept></student>
The following code, xsi:schemaLocation=”StudentSchema.xsd” is used to
reference the XML schema document (xsd) file which contains the definition of
this xml document.
Various xml validation tools are available which can be used to validate xml and
its schema document.
ACE Engineering College: Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
86 Web Technologies
Advantages
• Supports data types
• Supports namespaces
• XML schemas support a set of data types, similar to the ones used in most
common programming languages
• Provides the ability to define custom data types
• Easy to describe allowable content in the document
• Easy to validate the correctness of data
• Object oriented approach like inheritance and encapsulation can be used in
creating the document
• Easier to convert data between different data types
• Easy to define data formats
• Easy to define restrictions on data
• It is written in xml so any xml editor can be used to edit xml schema
Disadvantages
• Complex to design and learn
• Maintaining XML schema for large XML document slows down the
processing of XML document
PCDATA means parsed character data which is the text found between the start
tag and the end tag of an XML element.
Step 2: Write the XML document and reference the DTD file in it. Name it as
myXML.xml
<?xml version=”1.0”?>
<!DOCTYPE student SYSTEM student.dtd>
<student>
<name> Raj </name>
<regno>3212654556</regno>
<dept>CSE</dept>
</student>
!DOCTYPE student defines that the root element of this document is student and
links the myXML.xml file with the student.dtd file.
DOM Levels
• Level 1 Core: W3C Recommendation, October 1998
o It has feature for primitive navigation and manipulation of XML trees
o other Level 1 features are: All HTML features
• Level 2 Core: W3C Recommendation, November 2000
o It adds Namespace support and minor new features
ACE Engineering College: Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
88 Web Technologies
o other Level 2 features are: Events, Views, Style, Traversal and Range
• Level 3 Core: W3C Working Draft, April 2002
o It supports: Schemas, XPath, XSL, XSLT
Parsing the XML doc. using DOM methods and properties are called as tree
based approach whereas using SAX (Simple Api for Xml) methods and
properties are called as event based approach.
The following DOM java Classes are necessary to process the XML document:
• DocumentBuilderFactory class creates the instance of DocumentBuilder.
• DocumentBuilder produces a Document (a DOM) that conforms to the
DOM specification
• DOM is better for accessing a part of an XML document more than once.
• DOM is better for rearranging (sorting) the elements in a XML document.
• DOM is best for random access over SAX's sequential access.
• DOM can detect invalid nodes later in the document without any further
processing.
ACE Engineering College: Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
89 XML
Below is an example Java program which reads an XML document using DOM
API:
ACE Engineering College: Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
90 Web Technologies
Output:
Root element :company
----------------------------
ACE Engineering College: Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
91 XML
SAX Parser
SAX stands for Simple API for XML
SAX provides a mechanism for reading data from an XML document, SAX
parsers operate on each piece of the XML document sequentially.
It is a kind of event oriented approach for parsing the xml document.
An XML tree is not viewed as a data structure, but as a stream of events
generated by the parser.
SAX packages
• javax.xml.parsers: Describing the main classes needed for parsing
• org.xml.sax: Describing few interfaces for parsing
SAX classes
• SAXParser Defines the API that wraps an XMLReader implementation class
• SAXParserFactory Defines a factory API that enables applications to
configure and obtain a SAX based parser to parse XML documents
• ContentHandler Receive notification of the logical content of a document.
• DTDHandler Receive notification of basic DTD-related events.
• EntityResolver Basic interface for resolving entities.
• ErrorHandler Basic interface for SAX error handlers.
• DefaultHandler Default base class for SAX event handlers.
ACE Engineering College: Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
92 Web Technologies
• characters() – method called with the text contents in between the start and
end tags of an XML document element.
Below is an example Java program which reads an XML document using SAX
API:
ACE Engineering College: Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
93 XML
ACE Engineering College: Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
94 Web Technologies
End Element :firstname Start Element :lastname Last Name : mook kim End
Element :lastname Start Element :nickname Nick Name : mkyong End Element
:nickname Start Element :salary Salary : 100000
End Element :salary End Element :staff Start Element :staff
Start Element :firstname First Name : low
End Element :firstname Start Element :lastname Last Name : yin fong End
Element :lastname Start Element :nickname Nick Name : fong fong End
Element :nickname Start Element :salary Salary : 200000
End Element :salary End Element :staff
End Element :company
OBJECTIVEQUESTIONS
02. What is the correct syntax of the declaration which defines the XML version?
(A) <xml version="A.0" />
(B) <?xml version="A.0"?>
(C) <?xml version="A.0" />
(D) None of the above
02. Answer: (B)
ACE Engineering College: Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
96 Web Technologies
ACE Engineering College: Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
97 XML
01. Define an xml scheme show how an XML Scheme can be created
02. How do you define the elements of an XML document in an XML Schema?
04. Explain are the different revolution in which XML is playing a major role?
05. Explain and show how XML is useful in defining data for web applications.
07. Design an XML schema for hospital information management. Include every
feature available with schema.
08. Explain how styling XML with cascading style sheets is done for the library
information domain.
09. Discuss the important features of XML which make it more suitable than
HTML for creating web related services Creating A
01. Explain and show how XML is useful in defining data for web applications.
03. Design an XML schema for hospital information management. Include every
feature available with schema.
04. Explain how styling XML with cascading style sheets is done for the library
information domain.
05. Discuss the important features of XML which make it more Suitable than
HTML for creating web related services.
06. Define an xml scheme show how an XML Scheme can be created
08. When an element is called simple? How does it differ from a complex
element?
09. How do you define the elements of an XML document in an XML Schema?
10. How do you set default and fixed values for simple Elements?
ACE Engineering College: Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
99 XML
01. How XSL-FO Works (or) How would you produce PDF output using
XSL’s?
ACE Engineering College: Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)