0% found this document useful (0 votes)
88 views30 pages

Iwt 4 Unit

Xml And Php Document

Uploaded by

sarvagya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
88 views30 pages

Iwt 4 Unit

Xml And Php Document

Uploaded by

sarvagya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

Unit -4

XML Introduction
Extensible Markup Language (XML) is a markup language that defines a set of rules for encoding documents in
a format that is both human-readable and machine-readable. The design goals of XML focus on simplicity,
generality, and usability across the Internet. It is a textual data format with strong support via Unicode for
different human languages. Although the design of XML focuses on documents, the language is widely used
for the representation of arbitrary data structures such as those used in web services.
1. XML stands for extensible Markup Language
2. XML is a markup language like HTML
3. XML is designed to store and transport data
4. XML is designed to be self-descriptive
XML Simplifies Things
• It simplifies data sharing • It simplifies platform changes
• It simplifies data transport • It simplifies data availability
Example:
The XML is quite self-descriptive:
• It has sender information. • It has a heading.
• It has receiver information. • It has a message body.
The tags in the example below are not defined in any XML standard. These tags are “invented” by the author
of the XML document.HTML works with predefined tags like p tag, h1 tag; etc.While in XML, the author must
define both the tags and the document structure.
<?xml version="1.0" encoding="UTF-8"?> <message>
<to>MyReader</to>
<from>Chaitanya</from>
<msg>Welcome to beginnersbook.com</msg>
</message>
The top line <? xml version="1.0" encoding="UTF-8"?> is called XML prolog.
Basically XML above does not do anything. XML is just information wrapped in tags. User must require a
piece of software to send, receive, store, or display it.
XML has a variety of uses for Web, e-business, and portable applications.
The following are some of the many applications for which XML is useful:
• Web publishing: XML allows you to create interactive pages, allows the customer to customize those
pages, and makes creating e-commerce applications more intuitive. With XML, you store the data once
and then render that content for different viewers or devices based on style sheet processing using an
Extensible Style Language (XSL)/XSL Transformation (XSLT) processor.
• Web searching and automating Web tasks: XML defines the type of information contained in a
document, making it easier to return useful results when searching the Web:
For example, using HTML to search for books authored by Tom Brown is likely to return instances of the term
'brown' outside of the context of author. Using XML restricts the search to the correct context (for example,
the information contained in the <author> tag) and returns only the information that you want. By using XML,
Web agents and robots (programs that automate Web searches or other tasks) are more efficient and produce
more useful results.
• General applications: XML provides a standard method to access information, making it easier for
applications and devices of all kinds to use, store, transmit, and display data.
• E-business applications: XML implementations make electronic data interchange (EDI) more accessible
for information interchange, business-to-business transactions, and business-to-consumer
transactions.
• Metadata applications: XML makes it easier to express metadata in a portable, reusable format.

1
Unit -4
• Pervasive computing: XML provides portable and structured information types for display on pervasive
(wireless) computing devices such as personal digital assistants (PDAs), cellular phones, and others. For
example, WML (Wireless Markup Language) and VoiceXML are currently evolving standards for
describing visual and speech-driven wireless device interfaces.
Simple XML is a variation of XML containing only elements. All attributes are converted into elements. Not
having attributes or other xml elements such as the XML declaration / DTDs allows the use of simple and fast
parsers. This format is also compatible with mainstream XML parsers.
This simplified version on XML is a variant of the proposed XML language. It removes some features and adds
a few others. It mainly differs from XML in these aspects:
• There is no distinction between <foo></foo> and <foo/>, they can be used interchangeably.
• Documents can be nested: there may be <!doctype> declarations in the middle of a document.
• Default attribute declarations are scoped: they are valid until the end of the current element or
doctype.
• Whitespace handling is simplified: a newline immediately before a `<' and a newline immediately after
a `>' are ignored; no other whitespace is ignored by the parser (i.e., all other whitespace is passed on to
the application).
• Only character entities are allowed, no other types of entities exist.
• There is no internal document type subset. The allowed structure of the document can only be
specified in a separate document.
Example:
<?xml version="1.0" encoding="UTF-8"?>
<Agenda>
<type>gardening</type>
<Activity>
<type>Watering</type>
<golf-course>
<time>6:00</time>
</golf-course>
<yard>
<time>7:00</time>
</yard>
</Activity>
<Activity>
<type>cooking</type>
<lunch>
<time>12:00</time>
</lunch>
</Activity>
</Agenda>
Would represent:
<?xml version="1.0" encoding="UTF-8"?>
<Agenda type="gardening">
<Activity type="Watering">
<golf-course time="6:00"/>
<yard time="7:00"/>
</Activity>
<Activity type="cooking">

2
Unit -4
<lunch time="12:00"/>
</Activity>
</Agenda>
XML key components
Processing Instructions:
An XML Documents usually begins with the XML declaration statement called the Processing
Instructions .This statement provides information on how the XML file should be processed.
e.g. <?xml version =”1.0” encoding=”UTF-8”?>
The Processing Instruction statement uses the encoding property to specify the encoding scheme used
to create the XML file
Tags:
Tags are used to specify a name for a given piece of information. It is a means of identifying data. Data
is marked up using tags.
Elements:
Elements are the basic units used to identify and describe the data in XML. They are the building blocks
of an XML document. Elements are represented using tags.
Content:
Content refers to the information represented by the elements of an XML document. Consider the
following example:
<name>ram</name >
Here ram is content
Attributes:
Attributes provide additional information about the elements for which they are declared. An attribute
consists of a name-value pair. Consider the following example:
<Student_name S_ID = “101”>shanshak </ Student_name >
Entities:
An entity is a name that is associated with a block of data, such as chunk of text or a reference to an
external file that contains textual or binary information. It is a set of information that can be specifying
a single name.
Comments:
Comments are statements used to explain the XML code. They are used to provide documentation
information about the XML file or the application to which the file belongs. The parser ignores
comments entries during code execution.
XML DTD
DTD stands for Document Type Definition. The purpose of a DTD (Document Type Definition) is to define the
structure of an XML document. It defines the structure with a list of legal elements:
A DTD defines the structure and the legal elements and attributes of an XML document.
Valid XML Documents
A "Valid" XML document is "Well Formed", as well as it conforms to the rules of a DTD:
<? xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE note SYSTEM "Note.dtd">
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

3
Unit -4
The DOCTYPE declaration above contains a reference to a DTD file. The content of the DTD file is shown and
explained below.
XML DTD
The purpose of a DTD is to define the structure and the legal elements and attributes of an XML document:
Note.dtd:
<!DOCTYPE note
[
<!ELEMENT note (to,from,heading,body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>
]>
The DTD above is interpreted like this:
• !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" #PCDATA means parseable character data.
Using DTD for Entity Declaration
A DOCTYPE declaration can also be used to define special characters or strings, used in the document:
Example
<? xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE note [
<!ELEMENT note (to,from,heading,body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>
<!ENTITY nbsp "&#xA0;">
<!ENTITY writer "Writer: sar jain.">
<!ENTITY copyright "Copyright: @sar.">
]>
<note>
<to>sar</to>
<from>jain</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
<footer>&writer;&nbsp;&copyright;</footer>
</note>
An entity has three parts: it starts with an ampersand (&), then comes the entity name, and it ends with a
semicolon (;).
XML Schema

4
Unit -4
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>
The Schema above is interpreted like this:
• <xs:element name="note"> defines the element called "note"
• <xs:complexType> the "note" element is a complex type
• <xs:sequence> the complex type is a sequence of elements
• <xs:element name="to" type="xs:string"> the element "to" is of type string (text)
• <xs:element name="from" type="xs:string"> the element "from" is of type string
• <xs:element name="heading" type="xs:string"> the element "heading" is of type string
• <xs:element name="body" type="xs:string"> the element "body" is of type string
XML Schemas are More Powerful than DTD
• XML Schemas are written in XML
• XML Schemas are extensible to additions
• XML Schemas support data types
• XML Schemas support namespaces
Using XML with application
The Extensible Markup Language (XML) is a subset of SGML designed to enable generic SGML to be served,
received, and processed on the Web easily and efficiently. Because its format is not fixed, XML enables you to
design your own customized markup languages with which to create various types of documents. In the IDE,
XML documents are represented by XML nodes. The IDE provides tools to assist you in creating, editing,
checking, and validating the various XML document types it supports.
The IDE supports several types of XML documents, including:
• Cascading Style Sheet. A CSS provides a simple mechanism for formatting and adding style to HTML and
XML documents.
• Document Type Definition. A DTD describes the grammar that can be used in an XML file and indicates the
valid arrangement of the file's tags. It can exist as a prologue to an XML file (internal DTD) or as a separate file
(external DTD).
• Parsed Entity Objects. Parsed entity nodes represent parsed entity (.ent) files. If several of your XML
documents refer to a single piece of information, you can store that information in a parsed entity. Any
changes you make to the parsed entity are then automatically reflected in all of the documents that reference
it.
• XML Catalogs. XML catalogs provide mapping information that maps an external entity in an XML document
to the actual location of the document being referenced. You can use a catalog to redirect mappings for an
external entity, such as a DTD or XML file, to a different location.

5
Unit -4
• XSL Style sheet. XSL style sheets define transformation rules for your XML documents. You can perform an
XML transformation to transform the data in an XML document into the output of your choice, such as
formatted HTML or a text file
In this topic we are going to explain HTML applications using XML, HTTP, DOM, and JavaScript.
Step 1: Create Xml File Named Students.xml
Step 2: Create Html file Named ReadXml.html.
Step 3: Write JavaScript Function with using XMLHttpRequest API and DOM.
Display XML Data in an HTML Table
XML FILE
<?xml version="1.0" encoding="UTF-8"?>
<students>
<stu>
<name>s1</name>
<class>mtech</class>
</stu>
<stu>
<name>s2</name>
<class>mtech</class>
</stu>
<stu>
<name>s3</name>
<class>mtech</class>
</stu>
</students>
HTML FILE
<!DOCTYPE html>
<html>
<body>
<button type="button" onclick="loadXMLDoc()">Get my stu collection</button>
<br><br>
<script>
function loadXMLDoc() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
// code for older browsers
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xmlhttp.open("GET","students.xml",false);
xmlhttp.send();
}

6
Unit -4
function myFunction(xml) {
var i;
var xmlDoc = xml.responseXML;
var x = xmlDoc.getElementsByTagName("stu");
document.write("<table border=1>");
for (i=0;i<x.length;i++)
{
document.write("<tr>");
document.write("<td>");
document.write(x[i].getElementsByTagName("name")[0].childNodes[0].nodeValue);
document.write("</td>");
document.write("<td>");
document.write(x[i].getElementsByTagName("class")[0].childNodes[0].nodeValue);
document.write("</td>");
document.write("</tr>");
}
document.write("</table>");
}
</script>
</body>
</html>
Navigate Between the Elements
<!DOCTYPE html>
<html>
<body>
<div id='showstu'></div><br>
<input type="button" onclick="previous()" value="<<">
<input type="button" onclick="next()" value=">>">
<br><br>
<script>
var i = 0;
var x;
displaystu(i);
function displaystu(i) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this, i);
}
};
xmlhttp.open("GET", "students.xml", true);
xmlhttp.send();
}
function myFunction(xml,i) {
var xmlDoc = xml.responseXML;
x = xmlDoc.getElementsByTagName("stu");
document.getElementById("showstu").innerHTML =

7
Unit -4
"Name: " +x[i].getElementsByTagName("name")[0].childNodes[0].nodeValue +
"<br>Class: " + x[i].getElementsByTagName("class")[0].childNodes[0].nodeValue;
}
function next() {
if (i < x.length-1) {
i++;
displaystu(i);
}
}
function previous() {
if (i > 0) {
i--;
displaystu(i);
}
}
</script>
</body>
</html>
Show Album Information When Clicking On a Element
<!DOCTYPE html>
<html>
<body>
<p id='showstu'></p>
<br><br>
<script>
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
// code for older browsers
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xmlhttp.open("GET","students.xml",false);
xmlhttp.send();
var i;
var xmlDoc = xmlhttp.responseXML;
var x = xmlDoc.getElementsByTagName("stu");
document.write("<table border=1>");
for (i=0;i<x.length;i++)
{
document.write("<tr onclick='displaystu(" + i + ")'>");
document.write("<td>");

8
Unit -4
document.write(x[i].getElementsByTagName("name")[0].childNodes[0].nodeValue);
document.write("</td>");
document.write("<td>");
document.write(x[i].getElementsByTagName("class")[0].childNodes[0].nodeValue);
document.write("</td>");
document.write("</tr>");
}
document.write("</table>");
function displaystu(i) {
document.getElementById("showstu").innerHTML =
"Name:” + x[i].getElementsByTagName("name")[0].childNodes[0].nodeValue +
"<br>Class: " + x[i].getElementsByTagName("class")[0].childNodes[0].nodeValue;
}
</script>
</body>
</html>
Transforming xml using xsl and xslt
XSLT stands for Extensible Style Language Transformation. XSLT is powerful API for applying style to a XML
documents.
XML with XSLT you can apply formatting and transformation. Formatting is like CSS for applying styles. And
transformation mean XSLT give you control to transform XML to another form.
Original XML document is not changed. But base on original document create new document.
We define the web page structure tag that use for write XML document. Create a file called page.xml to
entering following code.
<?xml version="1.0"?>
<PAGE>
<HEADING>page heading</HEADING>
<ARTICLE>
<TITLE>article title</TITLE>
<DESCRIPTION>article description</DESCRIPTION>
</ARTICLE>
</PAGE>
XSLT Transform
Let’s start to write XSLT transform that will convert XML document and render to a HTML.
Define document type is XML along with document encoding:
<?xml version="1.0" encoding="ISO-8859-1"?>
Specifies the XSL Style Sheet and define the output method in <xsl:output> tag. Default output method XML
otherwise explicitly specify either TEXT or HTML.
Optionally you can also specify the indent attribute to produce indented spaced XML output.
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
...
<xsl:output method="html" indent="yes"/>
...
</xsl:stylesheet>
you can define number of templates contains using <xsl:template> tag. Every <xsl:template> tag contains
match attributes.
<xsl:apply-templates> process the children of the current node. In our case root element is current node.

9
Unit -4
Adding a root element that follow the following instruction,
<xsl:template match="/">
<html><body>
<xsl:apply-templates/>
</body></html>
</xsl:template>
HTML tag also process with <xsl:apply-templates/> tag. <xsl:apply-templates/> surrounding to a specified
HTML tag. You can also assign style attributes to apply inline CSS.
Process the child element
Now adding a child <HEADING> tag you have to add new template. In match attribute you have to write full
XPATH from the root element or simple write tag name.
But one thing clear if tag name use several time in your XML document and you want to apply style specific tag
you have to write the full XPATH other wise you can use only tag name to XML find itself.
<xsl:template match="/PAGE/HEADING">
<h1 align="center"> <xsl:apply-templates/> </h1>
</xsl:template>
Example Code:
page.xml
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="page.xsl"?>
<PAGE>
<HEADING>page heading</HEADING>
<ARTICLE>
<TITLE>article title</TITLE>
<DESCRIPTION>article description</DESCRIPTION>
</ARTICLE>
</PAGE>
page.xsl
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="html"/>
<xsl:template match="/">
<html><body>
<xsl:apply-templates/>
</body></html>
</xsl:template>
<xsl:template match="/PAGE/HEADING">
<h1 align="center"> <xsl:apply-templates/> </h1>
</xsl:template>
<xsl:template match="/PAGE/ARTICLE">
<div style="float:left;width:70%;"><xsl:apply-templates/> </div>
</xsl:template>
<xsl:template match="/PAGE/ARTICLE/TITLE">
<h3> <xsl:apply-templates/> </h3>
</xsl:template>
<xsl:template match="/PAGE/ARTICLE/DESCRIPTION">
<p> <xsl:apply-templates/> </p>

10
Unit -4
</xsl:template>
</xsl:stylesheet>
Introduction and Basic Syntax of PHP
PHP is a server side scripting language. That is used to develop Static websites or
Dynamic websites or Web applications. PHP stands for Hypertext Pre-processor, that
earlier stood for Personal Home Pages.
PHP scripts can only be interpreted on a server that has PHP installed.
The client computers accessing the PHP scripts require a web browser only.
PHP or Hypertext Pre-processor is a widely used open-source general purpose scripting
language and can be embedded with HTML. PHP files are saved with “.php” extension.
Basic Syntax:
<?php // PHP code goes here ?>
Example:
<!DOCTYPE html>
<html> <body> <h1>My first PHP page</h1> <?php echo "Hello World!"; ?>
</body></html>
Decision and Looping with Examples
PHP If Else
PHP if else statement is used to test condition. There are various ways to use if
statement in PHP.
• if
• if-else
• if-else-if
• nested if
PHP If Statement
PHP if statement is executed if condition is true.
Syntax
if(condition){
//code to be executed
}
Example
<?php
$num=12;
if($num<100){
echo "$num is less than 100";
}
?>
Output:
12 is less than 100
PHP if-else statement is executed whether condition is true or false.
Syntax
if(condition){
//code to be executed if true
}else{
//code to be executed if false
}
Example

11
Unit -4
<?php
$num=12;
if($num%2==0){
echo "$num is even number";
}else{
echo "$num is odd number";
}
?>
PHP Switch
PHP switch statement is used to execute one statement from multiple conditions. It
works like PHP if-else-if statement.
Syntax
switch(expression){
case value1:
//code to be executed
break;
case value2:
//code to be executed
break;
......
default:
code to be executed if all cases are not matched;
}
PHP Switch Example
<?php
$num=20;
switch($num){
case 10:
echo("number is equals to 10");
break;
case 20:
echo("number is equal to 20");
break;
case 30:
echo("number is equal to 30");
break;
default:
echo("number is not equal to 10, 20 or 30");
}
?>
Output:
number is equal to 20
PHP for Loop
PHP for loop can be used to traverse set of code for the specified number of times.
It should be used if number of iteration is known otherwise use while loop.
Syntax
for(initialization; condition; increment/decrement){

12
Unit -4
//code to be executed
}
Example
<?php
for($n=1;$n<=10;$n++){
echo "$n<br/>";
}
?>
Output:
1
2
3
4
5
6
7
8
9
10
PHP foreach Loop
PHP for each loop is used to traverse array elements.
Syntax
foreach( $array as $var ){
//code to be executed
}
?>
Example
<?php
$season=array("summer","winter","spring","autumn");
foreach( $season as $arr ){
echo "Season is: $arr<br />";
}
?>
Output:
Season is: summer
Season is: winter
Season is: spring
Season is: autumn
PHP While Loop
PHP while loop can be used to traverse set of code like for loop.
It should be used if number of iteration is not known.
Syntax
while(condition){
//code to be executed
}
Alternative Syntax
while(condition):

13
Unit -4
//code to be executed
endwhile;
PHP While Loop Example
<?php
$n=1;
while($n<=10){
echo "$n<br/>";
$n++;
}
?>
Output:
1
2
3
4
5
6
7
8
9
10
PHP do while loop
PHP do while loop can be used to traverse set of code like php while loop. The PHP do-
while loop is guaranteed to run at least once.
It executes the code at least one time always because condition is checked after
executing the code.
Syntax
do{
//code to be executed
}while(condition);
Example
<?php
$n=1;
do{
echo "$n<br/>";
$n++;
}while($n<=10);
?>
Output:
1……10
PHP Break
PHP break statement breaks the execution of current for, while, do-while, switch and for-
each loop. If you use break inside inner loop, it breaks the execution of inner loop only.
Syntax
jump statement;
break;
PHP Break: inside loop

14
Unit -4
Let's see a simple example to break the execution of for loop if value of i is equal to 5.
<?php
for($i=1;$i<=10;$i++){
echo "$i <br/>";
if($i==5){
break;
}
}
?>
Output:
1…5
PHP and HTML In an HTML page, PHP code is enclosed within special PHP tags. When a
visitor opens the page, the server processes the PHP code and then sends the output
(not the PHP code itself) to the visitor's browser. Actually it is quite simple to integrate
HTML and PHP. A PHP script can be treated as an HTML page, with bits of PHP inserted
here and there. Anything in a PHP script that is not contained within <?php ?> tags is
ignored by the PHP compiler and passed directly to the web browser.
Example
<html> <head></head> <body> <ul> <?php for($i=1;$i<=5;$i++){ ?>
<li>MenuItem <?php echo $i; ?> </li>
<?php } ?> </ul> </body> </html>
Arrays, Functions, Browser Control and Detection
Arrays
An array is a special variable, which can hold more than one value at a time. It is used to
hold multiple values of similar type in a single variable.
PHP Array Types
There are 3 types of array in PHP.
Indexed Array
Associative Array
Multidimensional Array
PHP Indexed Array
PHP index is represented by number which starts from 0. We can store number, string
and object in the PHP array. All PHP array elements are assigned to an index number by
default.
There are two ways to define indexed array:
1st way:
$season=array("summer","winter","spring","autumn");
2nd way:
$season[0]="summer";
$season[1]="winter";
$season[2]="spring";
$season[3]="autumn";
Example
File: array1.php
<?php
$season=array("summer","winter","spring","autumn");
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";

15
Unit -4
?>
Output:
Season are: summer, winter, spring and autumn
File: array2.php
<?php
$season[0]="summer";
$season[1]="winter";
$season[2]="spring";
$season[3]="autumn";
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
?>
Output:
Seasons are: summer, winter, spring and autumn
PHP Associative Array
We can associate name with each array elements in PHP using => symbol.
There are two ways to define associative array:
1st way:
$salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
2nd way:
$salary["Sonoo"]="350000";
$salary["John"]="450000";
$salary["Kartik"]="200000";
Example
File: arrayassociative1.php
<?php
$salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
echo "John salary: ".$salary["John"]."<br/>";
echo "Kartik salary: ".$salary["Kartik"]."<br/>";
?>
Output:
Sonoo salary: 350000
John salary: 450000
Kartik salary: 200000
PHP Multidimensional Array
PHP multidimensional array is also known as array of arrays. It allows you to store
tabular data in an array. PHP multidimensional array can be represented in the form of
matrix which is represented by row * column.
Definition
$emp = array
(
array(1,"sonoo",400000),
array(2,"john",500000),
array(3,"rahul",300000)
);
PHP Multidimensional Array Example
In this example, we are displaying 3 rows and 3 columns.

16
Unit -4
File: multiarray.php
<?php
$emp = array
(
array(1,"sonoo",400000),
array(2,"john",500000),
array(3,"rahul",300000)
);
for ($row = 0; $row < 3; $row++) {
for ($col = 0; $col < 3; $col++) {
echo $emp[$row][$col]." ";
}
echo "<br/>";
}
?>
Output:
1 sonoo 400000
2 john 500000
3 rahul 300000
Functions
PHP function is a piece of code that can be reused many times. It can take input as
argument list and return value. There are thousands of built-in functions in PHP.
In PHP, we can define Conditional function, Function within Function and Recursive
function also.
Advantage of PHP Functions
Code Reusability: PHP functions are defined only once and can be invoked many times,
like in other programming languages.
Less Code: It saves a lot of code because you don't need to write the logic many times.
By the use of function, you can write the logic only once and reuse it.
Easy to understand: PHP functions separate the programming logic. So it is easier to
understand the flow of the application because every logic is divided in the form of
functions.
PHP User-defined Functions
We can declare and call user-defined functions easily. Let's see the syntax to declare
user-defined functions.
Syntax
function functionname(){
//code to be executed
}
Note: Function name must be start with letter and underscore only like other labels in
PHP. It can't be start with numbers or special symbols.
PHP Functions Example
File: function1.php
<?php
function sayHello(){
echo "Hello PHP Function";
}

17
Unit -4
sayHello();//calling function
?>
Output:
Hello PHP Function
PHP Function Arguments
We can pass the information in PHP function through arguments which is separated by
comma.
PHP supports Call by Value (default), Call by Reference, Default argument values and
Variable-length argument list.
Let's see the example to pass single argument in PHP function.
File: functionarg.php
<?php
function sayHello($name){
echo "Hello $name<br/>";
}
sayHello("Sonoo");
sayHello("Vimal");
sayHello("John");
?>
Output:
Hello Sonoo
Hello Vimal
Hello John
PHP Call By Reference
Value passed to the function doesn't modify the actual value by default (call by value).
But we can do so by passing value as a reference.
By default, value passed to the function is call by value. To pass value as a reference, you
need to use ampersand (&) symbol before the argument name.
Let's see a simple example of call by reference in PHP.
File: functionref.php
<?php
function adder(&$str2)
{
$str2 .= 'Call By Reference';
}
$str = 'Hello ';
adder($str);
echo $str;
?>
Output:
Hello Call By Reference
PHP Function: Default Argument Value
We can specify a default argument value in function. While calling PHP function if you
don't specify any argument, it will take the default argument. Let's see a simple example
of using default argument value in PHP function.
File: functiondefaultarg.php
<?php

18
Unit -4
function sayHello($name="Sonoo"){
echo "Hello $name<br/>";
}
sayHello("Rajesh");
sayHello();//passing no value
sayHello("John");
?>
Output:
Hello Rajesh
Hello Sonoo
Hello John
PHP Function: Returning Value
Let's see an example of PHP function that returns value.
File: functiondefaultarg.php
<?php
function cube($n){
return $n*$n*$n;
}
echo "Cube of 3 is: ".cube(3);
?>
Output:
Cube of 3 is: 27
Browser Control and Detection
PHP get_browser() Function: The get_browser() function in PHP is an inbuilt function
which is used to tell the user about the browser's capabilities. The get_browser()
function looks up the user's browscap.ini file and returns the capabilities of the user's
browser.
Syntax: get_browser(user_agent, return_array)
Parameters Used: The get_browser() function in PHP accepts two parameters.
1. user_agent : It is an optional parameter which specifies the name of an HTTP user
agent. Default is the value of $HTTP_USER_AGENT.
2. return_array : It is an optional parameter which returns an array instead of an object
if it is set to True.
Exceptions:
1. The user_agent parameter can be bypassed with a NULL value.
2. The cookies value simply means that the browser itself is capable of accepting cookies
and does not mean the user has enabled the browser to accept cookies or not.
3. In order for this function to work the browscap configuration setting in php.ini must
point to the correct location of the browscap.ini file on your system.
Example
<?php echo $_SERVER['HTTP_USER_AGENT']; //using get_browser() to display
capabilities of the user browser
$mybrowser = get_browser();
print_r($mybrowser); ?>
String and Form Processing
String
PHP string is a sequence of characters i.e., used to store and manipulate text. PHP
supports only 256-character set and so that it does not offer native Unicode support.
19
Unit -4
We can create a string in PHP by enclosing the text in a single-quote. It is the easiest way
to specify string in PHP.
Following some examples are given to understand the single quoted PHP String in a better
way:
Example
<?php
$str='Hello text within single quote';
echo $str;
?>
Output: Hello text within single quote
We can store multiple line text, special characters, and escape sequences in a single-
quoted PHP string.
Example
<?php
$str1='Hello text
multiple line
text within single quoted string';
$str2='Using double "quote" directly inside single quoted string';
$str3='Using escape sequences \n in single quoted string';
echo "$str1 <br/> $str2 <br/> $str3";
?>
Output:
Hello text multiple line text within single quoted string
Using double "quote" directly inside single quoted string
Using escape sequences \n in single quoted string
We can store multiple line text, special characters, and escape sequences in a single-
quoted PHP string.
Example
<?php
$str1='Hello text
multiple line
text within single quoted string';
$str2='Using double "quote" directly inside single quoted string';
$str3='Using escape sequences \n in single quoted string';
echo "$str1 <br/> $str2 <br/> $str3";
?>
String function
1. Getting length of a String
PHP has a predefined function to get the length of a string. Strlen() displays the length of
any string. It is more commonly used in validating input fields where the user is limited to
enter a fixed length of characters.
Syntax: Strlen(string);
Example
<?php
echo strlen(“Welcome to Cloudways”);//will return the length of given string
?>
Output
20
2. Counting of the number of words in a String

20
Unit -4
Another function which enables display of the number of words in any specific string is
str_word_count(). This function is also useful in validation of input fields.
Syntax
Str_word_count(string)
Example
<?php
echo str_word_count(“Welcome to Cloudways”);//will return the number of words in a
string
?>
Output 3
3. Reversing a String
Strrev() is used for reversing a string. You can use this function to get the reverse version
of any string.
Syntax
Strev(string)
Example
<?php
echo strrev(“Welcome to Cloudways”);// will return the string starting from the end
?>
Output
syawduolC ot emocleW
4. Finding Text Within a String
Strpos() enables searching particular text within a string. It works simply by matching the
specific text in a string. If found, then it returns the specific position. If not found at all,
then it will return “False”. Strops() is most commonly used in validating input fields like
email.
Syntax
Strpos(string,text);
Example
<?php
echo strpos(“Welcome to Cloudways”,”Cloudways”);
?>
Output
11
5. Replacing text within a string
Str_replace() is a built-in function, basically used for replacing specific text within a
string.
Syntax
Str_replace(string to be replaced,text,string)
Example
<?php
echo str_replace(“cloudways”, “the programming world”, “Welcome to cloudways”);
?>
Output
Welcome to the programming world
6. Converting lowercase into Title Case
Ucwords() is used to convert first alphabet of every word into uppercase.
Syntax
Ucwords(string)
Example

21
Unit -4
<?php
echo ucwords(“welcome to the php world”);
?>
Output
Welcome To The Php World
7. Converting a whole string into UPPERCASE
Strtoupper() is used to convert a whole string into uppercase.
Syntax
Strtoupper(string);
Example
<?php
echo strtoupper(“welcome to cloudways”);// It will convert all letters of string into
uppercase
?>
Output
WELCOME TO CLOUDWAYS
8. Converting whole String to lowercase
Strtolower() is used to convert a string into lowercase.
Syntax
Strtolower(string)
Example
<?php
echo strtolower(“WELCOME TO CLOUDWAYS”);
?>
Output
welcome to cloudways
9. Repeating a String
PHP provides a built-in function for repeating a string a specific number of times.
Syntax
Str_repeat(string,repeat)
Example
<?php
echo str_repeat(“=”,13);
?>
Output
=============
10. Comparing Strings
You can compare two strings by using strcmp(). It returns output either greater than zero,
less than zero or equal to zero. If string 1 is greater than string 2 then it returns greater
than zero. If string 1 is less than string 2 then it returns less than zero. It returns zero, if the
strings are equal.
Syntax
Strcmp(string1,string2)
Example
<?php
echo strcmp(“Cloudways”,”CLOUDWAYS”);
echo “<br>”;
echo strcmp(“cloudways”,”cloudways”);//Both the strings are equal
echo “<br>”;
echo strcmp(“Cloudways”,”Hosting”);

22
Unit -4
echo “<br>”;
echo strcmp(“a”,”b”);//compares alphabetically
echo “<br>”;
echo strcmp(“abb baa”,”abb baa caa”);//compares both strings and returns the result in
terms of number of characters.
?>
Output
1
0
-1
-1
-4
11. Displaying part of String
Through substr() function you can display or extract a string from a particular position.
Syntax
substr(string,start,length)
Example
<?php
echo substr(“Welcome to Cloudways”,6).”<br>”;
echo substr(“Welcome to Cloudways”,0,10).”<br>”;
?>
Output
e to Cloudways
Welcome to
s
12. Removing white spaces from a String
Trim() is dedicated to remove white spaces and predefined characters from a both the
sides of a string.
Syntax
trim(string,charlist)
Example
<?php
$str = “Wordpess Hosting”;
echo $str . “<br>”;
echo trim(“$str”,”Wording”);
?>
Output
Wordpess Hosting
pess Host

Form Processing
The PHP superglobals $_GET and $_POST are used to collect form-data.
Before you can process the information, you need to create an HTML form that will send
information to your PHP script. There are two methods for sending data: POST and GET.
These two types of sending information are defined in your HTML form element's method
attribute. Also, you must specify the location of the PHP file that will process the
information.
Below is an HTML form that will send the data using the POST method Information sent
from a form with the POST method is invisible to others and has no limits on the amount
of information to send. Copy and paste this code and save it as form.html.

23
Unit -4
Example #1 A simple HTML form
<form action="action.php" method="post">
<p>Your name: <input type="text" name="name" /></p>
<p>Your age: <input type="text" name="age" /></p>
<p><input type="submit" /></p>
</form>
Example #2 Printing data from our form
Hi <?php echo $_POST['name']); ?>.
You are <?php echo $_POST['age']; ?> years old.

Files
PHP supports file handling which is used to read, write and append data to the file. File handling
is an important part of any web application. You often need to open and process a file for
different tasks. PHP has several functions for creating, reading, uploading, and editing
files.
Opening file:
fopen() function is used to open a file in PHP. Its required two arguments, first the file name and
then file opening mode.
The file may be opened in one of the following modes:
• r Read-only. Starts at the beginning of the file
• r+ Read/Write. Starts at the beginning of the file
• w Write only. Opens and clears the contents of the file; or creates a new file
if it doesn't exist
• w+ Read/Write. Opens and clears the contents of the file; or creates a new
file if it doesn't exist
• a Append. Opens and writes to the end of the file or creates a new file if it
doesn't exist
• a+ Read/Append. Preserves file content by writing to the end of the file
• x Write only. Creates a new file. Returns FALSE and an error if the file
already exists
• x+ Read/Write. Creates a new file. Returns FALSE and an error if the file
already exists
Example:
<?php
$fileName = "/doc/myFile.txt";
$fp = fopen($fileName,"r");
if( $fp == false )
{
echo ( "Error in opening file" );
exit();
}
?>
Reading file:
Once a file is opened using fopen() function then it can be read by a function
called fread(). This function requires two arguments. The file pointer and length in
bytes of the file must be expressed.
The files size can be calculated using the filesize() function which takes the file
name as its argument and returns the size of the file in bytes.
Example:
<?php
$fileName = "/doc/myFile.txt";
$fp = fopen($fileName,"r");
24
Unit -4
if( $fp == false )
{
echo ( "Error in opening file" );
exit();
}

$fileSize = filesize( $fileName );


$fileData = fread( $fp, $fileSize );
?>
The fgets() function is used to read a single line from a file, and after a call to this function, the file pointer has
moved to the next line.
Example:
<?php
$fileName = "/doc/myFile.txt";
$fp = fopen($fileName,"r");
if( $fp == false )
{
echo ( "Error in opening file" );
exit();
}

while(!feof($fp))
{
echo fgets($fp). "<br>";
}
?>

Writing File:
Using the PHP fwrite() function, a new file can be written, or text can be appended to an existing file. This function
requires two arguments, first specifying a file pointer and the string of data that is to be written. Optionally a third integer
argument can be used to specify the length of the data to write. If the third argument is used, file writing will stop after the
specified length has been reached.
Example:
<?php
$fileName = "/doc/myFile.txt";
$fp = fopen($fileName,"w");
if( $fp == false )
{
echo ( "Error in opening file" );
exit();
}
fwrite( $fp, "This is a sample text to write\n" );
?>
Closing file: In PHP it is not system critical to close all your files after using them because the file will auto close after
PHP code finishes execution.
You can close file, using fclose() function.
Example:
The fclose() function requires a file pointer as its argument and then returns true when the closure succeeds or false if it
fails.
<?php
$fileName = "/doc/myFile.txt";
$fp = fopen($fileName,"w");
if( $fp == false )
25
Unit -4
{
echo ( "Error in opening file" );
exit();
}
//some code to be executed
fclose( $fp );
?>
Cookies
A cookie is a small file with the maximum size of 4KB that the web server stores on the
client computer. A cookie created by a user can only be visible to them. Other users
cannot see its value. Most web browsers have options for disabling cookies, third party
cookies or both. If this is the case then PHP responds by passing the cookie token in the
URL.

Here,
1) A user requests for a page that stores cookies
2) The server sets the cookie on the user’s computer
3) Other page requests from the user will return the cookie name and value
Why and when to use Cookies?
• Http is a stateless protocol; cookies allow us to track the state of the application using
small files stored on the user’s computer. The path were the cookies are stored depends
on the browser. Internet Explorer usually stores them in Temporal Internet Files folder.
• Personalizing the user experience – this is achieved by allowing users to select their
preferences. The page requested that follow are personalized based on the set
preferences in the cookies.
• Tracking the pages visited by a user
Creating Cookies
The basic syntax used to create a cookie.
<?php
setcookie(cookie_name, cookie_value, [expiry_time], [cookie_path], [domain], [secure],
[httponly]);
?>
HERE,
• Php“setcookie” is the PHP function used to create the cookie.
• “cookie_name” is the name of the cookie that the server will use when retrieving
its value from the $_COOKIE array variable. It’s mandatory.
• “cookie_value” is the value of the cookie and its mandatory
• “[expiry_time]” is optional; it can be used to set the expiry time for the cookie
such as 1 hour. The time is set using the PHP time () functions plus or minus a
number of seconds greater than 0 i.e. time () + 3600 for 1 hour.

26
Unit -4
• “[cookie_path]” is optional; it can be used to set the cookie path on the server. The
forward slash “/” means that the cookie will be made available on the entire
domain. Sub directories limit the cookie access to the subdomain.
• “[domain]” is optional, it can be used to define the cookie access hierarchy
i.e. www.cookiedomain.com means entire domain
while www.sub.cookiedomain.com limits the cookie access
to www.sub.cookiedomain.com and its sub domains. Note it’s possible to have a
subdomain of a subdomain as long as the total characters do not exceed 253
characters.
• “[secure]” is optional, the default is false. It is used to determine whether the
cookie is sent via https if it is set to true or http if it is set to false.
• “[Httponly]” is optional. If it is set to true, then only client side scripting
languages i.e. JavaScript cannot access them.
The code below shows the implementation of the above example “cookies.php”.
<?php
setcookie("user_name", "sar", time()+ 60,'/'); // expires after 60 seconds
echo 'the cookie has been set for 60 seconds';
?>
Output:
The cookie has been set for 60 seconds
Retrieving the Cookie value
Create another file named “cookies_read.php” with the following code.
<?php
print_r($_COOKIE); //output the contents of the cookie array variable
?>
Output:
Array ([PHPSESSID] => h5onbf7pctbr0t68adugdp2611 [user_name] => sar)
Session
• A session is a global variable stored on the server.
• Each session is assigned a unique id which is used to retrieve stored values.
• Whenever a session is created, a cookie containing the unique session id is stored on
the user’s computer and returned with every request to the server. If the client browser
does not support cookies, the unique php session id is displayed in the URL
• Sessions have the capacity to store relatively large data compared to cookies.
• The session values are automatically deleted when the browser is closed. If you want to
store the values permanently, then you should store them in the database.
• Just like the $_COOKIE array variable, session variables are stored in the $_SESSION
array variable. Just like cookies, the session must be started before any HTML tags.
• You want to store important information such as the user id more securely on the
server where malicious users cannot temper with them.
• You want to pass values from one page to another.
• You want the alternative to cookies on browsers that do not support cookies.
• You want to store global variables in an efficient and more secure way compared to
passing them in the URL
• You are developing an application such as a shopping cart that has to temporary store
information with a capacity larger than 4KB.
Why and when to use Sessions?
• You want to store important information such as the user id more securely on the
server where malicious users cannot temper with them.
27
Unit -4
• You want to pass values from one page to another.
• You want the alternative to cookies on browsers that do not support cookies.
Creating a Session
In order to create a session, you must first call the PHP session_start function and then
store your values in the $_SESSION array variable.
Let’s suppose we want to know the number of times that a page has been loaded, we can
use a session to do that.
The code below shows how to create and retrieve values from sessions
<?php
session_start(); //start the PHP_session function
if(isset($_SESSION['page_count']))
{
$_SESSION['page_count'] += 1; }
else {
$_SESSION['page_count'] = 1; }
echo 'You are visitor number ' . $_SESSION['page_count'];
?>
Destroying Session Variables
The session_destroy() function is used to destroy the whole Php session variables.
If you want to destroy only a session single item, you use the unset() function.
The code below illustrates how to use both methods.
<?php
session_destroy(); //destroy entire session
?>
<?php
unset($_SESSION[' page_count']); //destroy product session item
?>
Object Oriented Programming with PHP
Object Oriented is an approach to software development that models application around
real world objects such as employees, cars, bank accounts, etc. A class defines the
properties and methods of a real world object. An object is an occurrence of a class.
The three major principles of OOP are;
• Encapsulation – this is concerned with hiding the implementation details and
only exposing the methods. The main purpose of encapsulation is to;
o Reduce software development complexity – by hiding the
implementation details and only exposing the operations, using a class
becomes easy.
o Protect the internal state of an object – access to the class variables is
via methods such as get and set, this makes the class flexible and easy
to maintain.
o The internal implementation of the class can be changed without
worrying about breaking the code that uses the class.
• Inheritance – this is concerned with the relationship between classes. The
relationship takes the form of a parent and child. The child uses the methods
defined in the parent class. The main purpose of inheritance is;
o Re-usability– a number of children, can inherit from the same parent.
This is very useful when we have to provide common functionality such
as adding, updating and deleting data from the database.
• Polymorphism – this is concerned with having a single form but many
different implementation ways. The main purpose of polymorphism is;

28
Unit -4
o Simplify maintaining applications and making them more extendable.
PHP is an object oriented scripting language; it supports all of the above principles.
The above principles are achieved via;
• Encapsulation - via the use of “get” and “set” methods etc.
• Inheritance - via the use of extends keyword
• Polymorphism - via the use of implements keyword
Create a class in PHP
The class keyword is used to define a class in PHP. Below are the rules for creating a
class in PHP.
• The class name should start with a letter
• The class name cannot be a PHP reserved word
• The class name cannot contain spaces
Syntax:
<?php
class classname
{
Data member;
Member function;
}
?>
Creating object: Syntax:
Classname objectname=new classname([argument]);
Accessing member of class: syntax
Objectname->membername();

Defining DataMember:
Syntax:
[Access specifier] $variable name;
Defining Member Function:
Syntax:
[Access specifier] function functionname([parameter])
{
//Statement;
}
Defining Constructor:
PHP provides you with a special method to help initialize object’s properties
called constructor.
To add a constructor to a class, you simply add a special method with the name __construct(). Whenever
you create a new object, PHP searches for this method and calls it automatically.
Syntax:
public function__construct([parameter])
{
//initialization of object properties.
}

<?php
class BankAccount
{
private $accountNumber;
private $totalBalance;
public function __construct($accountNo, $initialAmount)
{
29
Unit -4
$this->accountNumber = $accountNo;
$this->totalBalance = $initialAmount;
}
public function displayAmt()
{
echo “your bank amount is”.$totalBalance;
}
}
$account = new BankAccount('1243845355',2000);
$account->displayAmt();
?>
PHP destructor
PHP destructor allows you to clean up resources before PHP releases the object from the
memory. For example, you may create a file handle in the constructor and you close it in
the destructor.
To add a destructor to a class, you just simply add a special method called __destruct() as
follows:
public function __destruct()
{
// clean up resources here
}

30

You might also like