0% found this document useful (0 votes)
42 views21 pages

Adv. PHP Sybba (Ca) Chapter Iii - XML Ms. Pooja R. Kamble 3.1 Introduction XML

Uploaded by

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

Adv. PHP Sybba (Ca) Chapter Iii - XML Ms. Pooja R. Kamble 3.1 Introduction XML

Uploaded by

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

Adv.

PHP
SYBBA (CA) Chapter III – XML Ms. Pooja R. Kamble
3.1 Introduction XML
What is xml

o Xml (eXtensible Markup Language) is a mark up language.


o XML is designed to store and transport data.
o Xml was released in late 90’s. it was created to provide an easy to use and
store self describing data.
o XML became a W3C Recommendation on February 10, 1998.
o XML is not a replacement for HTML.
o XML is designed to be self-descriptive.
o XML is designed to carry data, not to display data.
o XML tags are not predefined. You must define your own tags.
o XML is platform independent and language independent.

What is mark-up language

A mark up language is a modern system for highlight or underline a document.

Students often underline or highlight a passage to revise easily, same in the


sense of modern mark up language highlighting or underlining is replaced by
tags.

Why xml

Platform Independent and Language Independent: The main benefit of xml


is that you can use it to take data from a program like Microsoft SQL, convert it
into XML then share that XML with other programs and platforms. You can
communicate between two platforms which are generally very difficult.

The main thing which makes XML truly powerful is its international
acceptance. Many corporation use XML interfaces for databases, programming,
office application mobile phones and more. It is due to its platform independent
feature.

Features and Advantages of XML

XML is widely used in the era of web development. It is also used to simplify
data storage and data sharing.

The main features or advantages of XML are given below.


Adv. PHP
SYBBA (CA) Chapter III – XML Ms. Pooja R. Kamble
1) XML separates data from HTML

If you need to display dynamic data in your HTML document, it will take a lot
of work to edit the HTML each time the data changes.

With XML, data can be stored in separate XML files. This way you can focus
on using HTML/CSS for display and layout, and be sure that changes in the
underlying data will not require any changes to the HTML.

With a few lines of JavaScript code, you can read an external XML file and
update the data content of your web page.

2) XML simplifies data sharing

In the real world, computer systems and databases contain data in incompatible
formats.

XML data is stored in plain text format. This provides a software- and
hardware-independent way of storing data.

This makes it much easier to create data that can be shared by different
applications.

3) XML simplifies data transport

One of the most time-consuming challenges for developers is to exchange data


between incompatible systems over the Internet.

Exchanging data as XML greatly reduces this complexity, since the data can be
read by different incompatible applications.

4) XML simplifies Platform change

Upgrading to new systems (hardware or software platforms), is always time


consuming. Large amounts of data must be converted and incompatible data is
often lost.

XML data is stored in text format. This makes it easier to expand or upgrade to
new operating systems, new applications, or new browsers, without losing data.

5) XML increases data availability

Different applications can access your data, not only in HTML pages, but also
from XML data sources.
Adv. PHP
SYBBA (CA) Chapter III – XML Ms. Pooja R. Kamble
With XML, your data can be available to all kinds of "reading machines"
(Handheld computers, voice machines, news feeds, etc), and make it more
available for blind people, or people with other disabilities.

6) XML can be used to create new internet languages

A lot of new Internet languages are created with XML.

Here are some examples:

o XHTML
o WSDL for describing available web services
o WAP and WML as markup languages for handheld devices
o RSS languages for news feeds
o RDF and OWL for describing resources and ontology
o SMIL for describing multimedia for the web

HTML vs XML

There are many differences between HTML (Hyper Text Markup Language)
and XML (eXtensible Markup Language). The important differences are given
below:

No. HTML XML

1) HTML is used to display XML is a software and hardware


data and focuses on how independent tool used to transport and
data looks. store data. It focuses on what data is.

2) HTML is a markup XML provides a framework to define


language itself. markup languages.

3) HTML is not case XML is case sensitive.


sensitive.

4) HTML is a presentation XML is neither a presentation language


language. nor a programming language.
Adv. PHP
SYBBA (CA) Chapter III – XML Ms. Pooja R. Kamble

5) HTML has its own You can define tags according to your
predefined tags. need.

6) In HTML, it is not XML makes it mandatory to use a


necessary to use a closing tag.
closing tag.

7) HTML is static because XML is dynamic because it is used to


it is used to display data. transport data.

8) HTML does not XML preserve whitespaces.


preserve whitespaces.

3.2 XML document Structure


Structure of an XML document:
1. An XML document contains exactly one root element: the start tag of the
XML document, and it contains all other elements.
1 <root>
2 <section>
3 <sub-section></sub-section>
4 <sub-section></sub-section>
5 </section>
6
7 <section>
8 <sub-section></sub-section>
9 <sub-section></sub-section>
10 </section>
11 <root>
2. XML documents may begin with a prolog that appears before the root
element. It has the metadata about the XML document, such as character
encoding, document structure, and style sheets. For example,
1 <?xml version="1.0" encoding="UTF-8"?>
3. A tag in XML is a case-sensitive markup construct that begins
with < and ends with > . A tag can be:
Adv. PHP
SYBBA (CA) Chapter III – XML Ms. Pooja R. Kamble
 A start-tag, such as <name>
 An end-tag, such as </name>
 An empty-element tag, such as <name/>
4. An element in XML is formed by characters between the start-tag and the
end-tag. For example, <name>John Snow</name> . It can also consist
only of an empty-element tag. For example, <name/> .
5. XML elements can have attributes which exists within a start-tag or
empty-element tag.
An attribute consists of a name–value pair. For example,
1 <img src="screenshot.png" alt="screenshot" />
6. Here the names of the attributes are src and alt, and their values
are screenshot.png and screenshot, respectively.

What is a DTD?

DTD stands for Document Type Definition.

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>

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:
Adv. PHP
SYBBA (CA) Chapter III – XML Ms. Pooja R. Kamble
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"

NOTE :#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 [
<!ENTITY nbsp "&#xA0;">
<!ENTITY writer "Writer: Donald Duck.">
<!ENTITY copyright "Copyright: W3Schools.">
]>

<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
Adv. PHP
SYBBA (CA) Chapter III – XML Ms. Pooja R. Kamble
<body>Don't forget me this weekend!</body>
<footer>&writer;&nbsp;&copyright;</footer>
</note>

3.3 PHP and XML


What is PHP? A popular general-purpose scripting language that is especially
suited to web development. Fast, flexible and pragmatic, PHP powers
everything from your blog to the most popular websites in the world.
What is XML? A simple, very flexible text format. A markup language that
defines a set of rules for encoding documents in a format that is both human-
readable and machine-readable.

3.4 XML parser


XML Parsers

An XML parser is a program that translates the XML document into an XML
Document Object Model (DOM) Object.

The XML DOM Object can then be manipulated using JavaScript, Python, and
PHP etc.

An XML parser is a software library or package that provides interfaces for


client applications to work with an XML document. The XML Parser is
designed to read the XML and create a way for programs to use XML.

XML parser validates the document and check that the document is well
formatted.

Let's understand the working of XML parser by the figure given below:
Adv. PHP
SYBBA (CA) Chapter III – XML Ms. Pooja R. Kamble

What is an XML Parser?

To read and update, create and manipulate an XML document, you will need an
XML parser.

In PHP there are two major types of XML parsers:

 Tree-Based Parsers
 Event-Based Parsers

Tree-Based Parsers

Tree-based parsers holds the entire document in Memory and transforms the
XML document into a Tree structure. It analyzes the whole document, and
provides access to the Tree elements (DOM).

This type of parser is a better option for smaller XML documents, but not for
large XML document as it causes major performance issues.

Example of tree-based parsers:

 SimpleXML
 DOM

Event-Based Parsers

Event-based parsers do not hold the entire document in Memory, instead, they
read in one node at a time and allow you to interact with in real time. Once you
move onto the next node, the old one is thrown away.

This type of parser is well suited for large XML documents. It parses faster and
consumes less memory.

Example of event-based parser:

 SAX

These are the two main types of XML Parsers:

1. DOM
2. SAX
Adv. PHP
SYBBA (CA) Chapter III – XML Ms. Pooja R. Kamble
DOM (Document Object Model)

A DOM document is an object which contains all the information of an XML


document. It is composed like a tree structure. The DOM Parser implements a
DOM API. This API is very simple to use.

Features of DOM Parser

A DOM Parser creates an internal structure in memory which is a DOM


document object and the client applications get information of the original XML
document by invoking methods on this document object.

DOM Parser has a tree based structure.

Advantages

1) It supports both read and write operations and the API is very simple to use.

2) It is preferred when random access to widely separated parts of a document is


required.

Disadvantages

1) It is memory inefficient. (Consumes more memory because the whole XML


document needs to load into memory).

2) It is comparatively slower than other parsers.

SAX (Simple API for XML)

A SAX Parser implements SAX API. This API is an event based API and less
intuitive.

Features of SAX Parser

It does not create any internal structure.

Clients does not know what methods to call, they just overrides the methods of
the API and place his own code inside method.

It is an event based parser, it works like an event handler in Java.


Adv. PHP
SYBBA (CA) Chapter III – XML Ms. Pooja R. Kamble
Advantages

1) It is simple and memory efficient.

2) It is very fast and works for huge documents.

Disadvantages

1) It is event-based so its API is less intuitive.

2) Clients never know the full information because the data is broken into
pieces.

3.5 The document object model

What is XML DOM

DOM is an acronym stands for Document Object Model. It defines a standard


way to access and manipulate documents. The Document Object Model (DOM)
is a programming API for HTML and XML documents. It defines the logical
structure of documents and the way a document is accessed and manipulated.

As a W3C specification, one important objective for the Document Object


Model is to provide a standard programming interface that can be used in a wide
variety of environments and applications. The Document Object Model can be
used with any programming language.

XML DOM defines a standard way to access and manipulate XML documents.

What does XML DOM

The XML DOM makes a tree-structure view for an XML document.

We can access all elements through the DOM tree.

We can modify or delete their content and also create new elements. The
elements, their content (text and attributes) are all known as nodes.

For example, consider this table, taken from an HTML document:

<TABLE>
<ROWS>
Adv. PHP
SYBBA (CA) Chapter III – XML Ms. Pooja R. Kamble
<TR>
<TD>A</TD>
<TD>B</TD>
</TR>
<TR>
<TD>C</TD>
<TD>D</TD>
</TR>
</ROWS>
</TABLE>

The Document Object Model represents this table like this:

3.6 The simple XML extension


The SimpleXML Parser

SimpleXML is a tree-based parser.

SimpleXML provides an easy way of getting an element's name, attributes and


textual content if you know the XML document's structure or layout.

SimpleXML turns an XML document into a data structure you can iterate
through like a collection of arrays and objects.
Adv. PHP
SYBBA (CA) Chapter III – XML Ms. Pooja R. Kamble
Compared to DOM or the Expat parser, SimpleXML takes a fewer lines of code
to read text data from an element.

PHP SimpleXML - Read From String

The PHP simplexml_load_string() function is used to read XML data from a


string.

Assume we have a variable that contains XML data, like this:

$myXMLData =
"<?xml version='1.0' encoding='UTF-8'?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>";

The example below shows how to use the simplexml_load_string() function to


read XML data from a string:

Example
<?php
$myXMLData =
"<?xml version='1.0' encoding='UTF-8'?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>";

$xml=simplexml_load_string($myXMLData) or die("Error: Cannot create


object");
print_r($xml);
?>

The output of the code above will be:


Adv. PHP
SYBBA (CA) Chapter III – XML Ms. Pooja R. Kamble
SimpleXMLElement Object ( [to] => Tove [from] => Jani [heading] =>
Reminder [body] => Don't forget me this weekend! )

Error Handling Tip: Use the libxml functionality to retrieve all XML errors
when loading the document and then iterate over the errors. The following
example tries to load a broken XML string:

Example
<?php
libxml_use_internal_errors(true);
$myXMLData =
"<?xml version='1.0' encoding='UTF-8'?>
<document>
<user>John Doe</wronguser>
<email>[email protected]</wrongemail>
</document>";

$xml = simplexml_load_string($myXMLData);
if ($xml === false) {
echo "Failed loading XML: ";
foreach(libxml_get_errors() as $error) {
echo "<br>", $error->message;
}
} else {
print_r($xml);
}
?>

The output of the code above will be:

Failed loading XML:


Opening and ending tag mismatch: user line 3 and wronguser
Opening and ending tag mismatch: email line 4 and wrongemail
PHP SimpleXML - Read From File

The PHP simplexml_load_file() function is used to read XML data from a file.

Assume we have an XML file called "note.xml", that looks like this:

<?xml version="1.0" encoding="UTF-8"?>


<note>
Adv. PHP
SYBBA (CA) Chapter III – XML Ms. Pooja R. Kamble
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

The example below shows how to use the simplexml_load_file() function to


read XML data from a file:

Example
<?php
$xml=simplexml_load_file("note.xml") or die("Error: Cannot create object");
print_r($xml);
?>

The output of the code above will be:

SimpleXMLElement Object ( [to] => Tove [from] => Jani [heading] =>
Reminder [body] => Don't forget me this weekend! )
3.7 Changing a value with simple XML
PHP SimpleXML - Get Node Values

Get the node values from the "note.xml" in above example file is included:

Example
<?php
$xml=simplexml_load_file("note.xml") or die("Error: Cannot create object");
echo $xml->to . "<br>";
echo $xml->from . "<br>";
echo $xml->heading . "<br>";
echo $xml->body;
?>

The output of the code above will be:

Tove
Jani
Reminder
Don't forget me this weekend!
Adv. PHP
SYBBA (CA) Chapter III – XML Ms. Pooja R. Kamble
Another XML File

Assume we have an XML file called "books.xml", that looks like this:

<?xml version="1.0" encoding="utf-8"?>


<bookstore>
<book category="COOKING">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="WEB">
<title lang="en-us">XQuery Kick Start</title>
<author>James McGovern</author>
<year>2003</year>
<price>49.99</price>
</book>
<book category="WEB">
<title lang="en-us">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
PHP SimpleXML - Get Node Values of Specific Elements

The following example gets the node value of the <title> element in the first and
second <book> elements in the "books.xml" file:

Example
<?php
$xml=simplexml_load_file("books.xml") or die("Error: Cannot create object");
echo $xml->book[0]->title . "<br>";
Adv. PHP
SYBBA (CA) Chapter III – XML Ms. Pooja R. Kamble
echo $xml->book[1]->title;
?>

The output of the code above will be:

Everyday Italian
Harry Potter

PHP SimpleXML - Get Node Values - Loop

The following example loops through all the <book> elements in the
"books.xml" file, and gets the node values of the <title>, <author>, <year>, and
<price> elements:

Example
<?php
$xml=simplexml_load_file("books.xml") or die("Error: Cannot create object");
foreach($xml->children() as $books) {
echo $books->title . ", ";
echo $books->author . ", ";
echo $books->year . ", ";
echo $books->price . "<br>";
}
?>

The output of the code above will be:

Everyday Italian, Giada De Laurentiis, 2005, 30.00


Harry Potter, J K. Rowling, 2005, 29.99
XQuery Kick Start, James McGovern, 2003, 49.99
Learning XML, Erik T. Ray, 2003, 39.95

PHP SimpleXML - Get Attribute Values

The following example gets the attribute value of the "category" attribute of the
first <book> element and the attribute value of the "lang" attribute of the <title>
element in the second <book> element:
Adv. PHP
SYBBA (CA) Chapter III – XML Ms. Pooja R. Kamble
Example
<?php
$xml=simplexml_load_file("books.xml") or die("Error: Cannot create object");
echo $xml->book[0]['category'] . "<br>";
echo $xml->book[1]->title['lang'];
?>

The output of the code above will be:

COOKING
en
PHP SimpleXML - Get Attribute Values - Loop

The following example gets the attribute values of the <title> elements in the
"books.xml" file:

Example
<?php
$xml=simplexml_load_file("books.xml") or die("Error: Cannot create object");
foreach($xml->children() as $books) {
echo $books->title['lang'];
echo "<br>";
}
?>

The output of the code above will be:

en
en
en-us
en-us

Program:-
1:-Write a PHP script to create XML file named “Course.xml”
Store the details of 5 students who are in SYBBACA.
Adv. PHP
SYBBA (CA) Chapter III – XML Ms. Pooja R. Kamble
<Course>
<SYBBA CA>
<Student name> ABC</Student name>
<Class name> A Class</Class name>
<percentage>90 </percentage>
</SYBBA CA>
<SYBBA CA>
<Student name> XYZ</Student name>
<Class name> B Class</Class name>
<percentage>70 </percentage>
</SYBBA CA>
<SYBBA CA>
<Student name> PQR</Student name>
<Class name> C Class</Class name>
<percentage>50 </percentage>
</SYBBA CA>
<SYBBA CA>
<Student name> LMN</Student name>
<Class name> A Class</Class name>
<percentage>92 </percentage>
</SYBBA CA>
<SYBBA CA>
<Student name> YZW</Student name>
<Class name> A Class</Class name>
<percentage>85 </percentage>
</SYBBA CA>
</Course>
2:-Write PHP script to create a CD catalog using XML file.
Xml file :

<?xml version='1.0' encoding='UTF-8' ?>

<CD>
<cd type='music'>
<name>silent_songs</name>
<launch-date>5-6-2014</launch-date>
<composer>A-R-Rehman</composer>
</cd>
Adv. PHP
SYBBA (CA) Chapter III – XML Ms. Pooja R. Kamble
<cd type='music'>
<name>Hip-Hop</name>
<launch-date>4-8-2011</launch-date>
<composer>Yo-Yo-Honey singh</composer>
</cd>

<cd type='music'>
<name>love track</name>
<launch-date>6-9-2000</launch-date>
<composer>Arjit Singh</composer>
</cd>
</CD>

Php file :

<?php
$xml=simplexml_load_file('CD.xml');
var_dump($xml);
?>

3:- Create a XML file which gives details of books available in “ABC Bookstore”
from following categories
1) Technical
2) Cookin
3) YOGA

Xml file :

<?xml version='1.0' ?>


<ABC_Bookstore>
<books category="technical">
<book_no>1</book_no>
<book_name>def</book_name>
<author_name>xxx</author_name>
<price>100</price>
<year>1990</year>
</books>
<books category="Cooking">
<book_no>2</book_no>
Adv. PHP
SYBBA (CA) Chapter III – XML Ms. Pooja R. Kamble
<book_name>ccc</book_name>
<author_name>aaa</author_name>
<price>200</price>
<year>1950</year>
</books>
<books category="YOGA">
<book_no>3</book_no>
<book_name>ddd</book_name>
<author_name>zzz</author_name>
<price>150</price>
<year>2016</year>
</books>
</ABC_Bookstore>
4:- Write a PHP script to generate an XML in the following format
HTML file
<html>
<head>

<title>Create XML</title>
</head>
<form action=book.php.php method=get>
Enter Book Title<input type=text name=txtTitle></br>
Enter Publication<input type=text name=publ></br>
<input type=submit value="submit">
</form>
</html>

PHP File
<?php

echo "Links data posted";


$ele=$_GET['txtTitle'];
$att=$_GET['publ'];
$xmltags="<?xml version=1.0?>";
$xmltags=$xmltags."<Bookstore>";
$xmltags=$xmltags."<Books>";
$xmltags=$xmltags."<PHP>";
$xmltags=$xmltags."<title>";
$xmltags=$xmltags.$ele;
$xmltags=$xmltags."</title>";
$xmltags=$xmltags."<publication>";
$xmltags=$xmltags.$att;
Adv. PHP
SYBBA (CA) Chapter III – XML Ms. Pooja R. Kamble
$xmltags=$xmltags."</attrib>";
$xmltags=$xmltags."</PHP>";
$xmltags=$xmltags."</Books>";
$xmltags=$xmltags."</Bookstore>";

if($fp=fopen("books.xml","w"))
{
if($wt=fwrite($fp,$xmltags))
{
echo "File created";
}
else
echo "Not write";
}
else
echo "Not opened";

?>

You might also like