0% found this document useful (0 votes)
117 views32 pages

CSE2045Y Web Application Development: XML, XSD, XSLT With PHP

1. The document discusses an XML, XSD, XSLT and PHP lecture that covers validating XML against a schema in PHP, accessing XML nodes from PHP using SimpleXML, and transforming XML in PHP using XSLT. 2. It provides an example scenario where an organization receives XML data from another organization, validates it against an XSD schema in PHP, accesses the XML nodes using SimpleXML to insert the data into its database, and transforms the XML using XSLT to display it in the browser. 3. It also discusses using the XML DOM and JavaScript to dynamically build and submit an XML document from the browser to the server.

Uploaded by

splokbov
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)
117 views32 pages

CSE2045Y Web Application Development: XML, XSD, XSLT With PHP

1. The document discusses an XML, XSD, XSLT and PHP lecture that covers validating XML against a schema in PHP, accessing XML nodes from PHP using SimpleXML, and transforming XML in PHP using XSLT. 2. It provides an example scenario where an organization receives XML data from another organization, validates it against an XSD schema in PHP, accesses the XML nodes using SimpleXML to insert the data into its database, and transforms the XML using XSLT to display it in the browser. 3. It also discusses using the XML DOM and JavaScript to dynamically build and submit an XML document from the browser to the server.

Uploaded by

splokbov
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/ 32

CSE2045Y

Web Application Development

Lecture 8
XML, XSD, XSLT with PHP

1
Agenda
• XML, XSD, XSLT and PHP
• Validate XML against Schema in PHP
• Accessing XML nodes from PHP
– Accessing nodes using SimpleXML
• Transform XML in PHP
– Stylesheet
– DOM Document
• XML DOM and JavaScript
– Sample scenarios

2
Recap
• XML is used to transfer data.
– e.g. From one business partner to another.

• XSD is used to validate the data transferred.


– e.g. Validate the data received by one business
partner.

• XSLT is used to transform the XML data.


– e.g. Convert into a form that can be displayed by
the browser.
3
Introduction
• Question: How would all of these be integrated in our web
model?

• Possible Scenario:
1. Data from Organisation1 sent to Organisation2.
2. Organisation2 needs to process the data either by
displaying it in appropriate format or adding it to its own
database.
4
Possible Scenario
1. XML Data from Organisation1 sent to Organisation2.
<?xml version=“1.0”?>
<modules>
<module>
<modulecode>CSE2045y</modulecode>
<moduledesc>Web Application Development</moduledesc>
</module>

<module>
<modulecode>CSE1240</modulecode>
<moduledesc>Database Systems</moduledesc>
</module>
</modules>

5
Possible Scenario
2. Suppose Organisation2 wants to insert the
data into its own database.
– However, Organisation2 needs to validate the data
against a Schema before the database operation.

6
Schema (modules.xsd)
<?xml version="1.0" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="modules">
<xs:complexType>
<xs:sequence>
<xs:element name="module" maxOccurs="unbounded" minOccurs="1">
<xs:complexType>
<xs:sequence>
<xs:element name="modulecode" type="xs:string"/>
<xs:element name="moduledesc" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema> 7
Validate XML against Schema in PHP
• We need to validate the XML document against the
Schema in PHP:
$xml_Doc = new DOMDocument();
$xml_Doc->loadXML($modules);

if(!$xml_Doc->schemaValidate('modules.xsd'))
echo "Your xml is NOT valid";

• Assume the XML is captured in the variable $modules.


• Note:
– $xml_Doc->loadXML($modules) is used to load the XML
contained within a string variable.
– $xml_Doc->load($modules) is used to load XML either
from a Stream, TextReader, URL or XMLReader.
8
Validate XML against Schema in PHP
• The schemaValidate() method is associated
with the DOMDocument object.

• DOM is available both at server and JavaScript


client side.

• The Schema (modules.xsd) is stored on the


Organisation2 server to validate the XML.
9
Accessing XML nodes from PHP
• After validation, PHP needs to access the different XML
nodes for processing.

• Simplexml is a PHP 5 API that allows easy processing


of XML:
– Elements as well as attributes can easily be accessed
without the hassle of DOM.
– The SimpleXML extension provides a very simple and
easily usable toolset to convert XML to an object that can
be processed with normal property selectors and array
iterators.

• In our example, we want to access the elements before


adding them to a database. 10
Accessing nodes using SimpleXML (1)

$xml_Doc = new DOMDocument();


$xml_Doc->loadXML($modules);
$xml_modules = simplexml_import_dom($xml_Doc);

foreach ($xml_modules->module as $module){


$modulecode=$module->modulecode;
$moduledesc= $module->moduledesc;

if($modulecode!="" && $modulecode!=null){


//Check if data exists before inserting
$sql_select="SELECT * FROM modules WHERE
modulecode='$modulecode'";
$Rs = mysql_query($sql_select);
11
Accessing nodes using SimpleXML (2)
//insert only if the data has not been inserted before
if (mysql_num_rows($Rs) < 1){
//we want to insert data
$sql_insert="INSERT INTO modules (modulecode, moduledesc)
values ('$modulecode', '$moduledesc')";

if (!mysql_query($sql_insert,$con)){
die('Error: ' . mysql_error());}
}//end if

}//end if
}//end foreach

//close database connection


mysql_close($con);
12
Transform XML in PHP
• Suppose we want our PHP codes to format the data (from
Organisation1) as XML and display it on the browser.

• In other words, we need to apply an XSLT dynamically to the


XML at PHP Level.

13
Transform XML in PHP
Option 1
• Apply a stylesheet (XSLT) to the resulting XML
string and output the XML to the browser.
//Build an XML to display the modules.
header('Content-Type: text/xml');
$xml_output = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>";
$xml_output=$xml_output."<?xml-stylesheet type=\"text/xsl\"
href=\"modules.xsl\"?>";
$xml_output = $xml_output.$modules;
echo $xml_output;

• Refer to addmodulexml.php for the complete


set of codes.
14
Transform XML in PHP
Option 2
• Using DOM Document:
$xslDoc = new DOMDocument();
$xslDoc->load("modules.xsl");

$proc = new XSLTProcessor();//PHP5


$proc->importStylesheet($xslDoc);

echo $proc->transformToXML($xml_Doc);

• Note: php5-xsl is required to have access to the


XSLTProcessor object.
• Refer to addmodulexml.php for the complete set
of codes.
15
Activity 1
• Consider the following xml file, collection.xml.
<?xml version="1.0"?>
<collection>
<cd>
<title>Fight for your mind</title>
<artist>Ben Harper</artist>
<year>1995</year>
</cd>

<cd>
<title>Electric Ladyland</title>
<artist>Jimi Hendrix</artist>
<year>1997</year>
</cd>
</collection>
16
Activity 1
• The corresponding xslt file, collection.xsl, is as
follows:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:param name="owner" select="'Nicolas Eliaszewicz'"/>

<xsl:template match="collection">
Hey! Welcome to <xsl:value-of select="$owner"/>'s sweet CD
collection!
<xsl:apply-templates/>
</xsl:template>

<xsl:template match="cd">
<h1><xsl:value-of select="title/text()"/></h1>
<h2>by <xsl:value-of select="artist/text()"/> - <xsl:value-of
select="year/text()"/></h2>
<hr />
</xsl:template>

</xsl:stylesheet> 17
Activity 1
• The xslt file will display the data in the
browser:

18
Activity 1
a) Write the xsd file, collection.xsd.

b) Write the PHP codes to display the xml file:


– Validate the xml file against the xsd file.
– If the xml file is valid, apply the xslt to display the
data in the browser using DOM Document.
– Otherwise, display an error message.

19
XML DOM and JavaScript
• Scenario 1:
– The XML is being built at a browser level using DOM.
– Step 1: An XML string with only the root is created.
– Step 2: This XML string is converted into an XML document
object using the function loadXMLString(txt).
– Step 3: Data is added to the XML by calling addTableRow( )
which in turn calls insertModule( ).
– The display is recomputed by traversing the XML
document and displaying the different nodes in a table.
– Step 4: When the user decides to submit the data, the
XML document is serialized into a string by the function
encodeItems() and the string is placed in a hidden field
and sent to the server for processing.
20
XML DOM and JavaScript
• Important DOM functions used in the example
are:
– createElement
– appendChild
– createTextNode
– childNodes[ ]
– firstChild
– nodeValue

21
Scenario 1 Explained (HTML file)
<head><script> … JavaScript goes here … </script></head>
<body>
<form action=addmodulexml.php method=post onsubmit="return encodeItems()">
<table id=table_modules>
<tr>
<th width=200>Module Code</th>
<th width=200>Module Name</th>
<th>
</tr>
<tr>
<td><input type=text name=txt_modulecode></td>
<td><input type=text name=txt_moduledesc></td>
<td><button onclick="return addTableRow()">Add Module</button></td>
</tr>
</table>
<br><br>
<div id="div_modules"></div>
<input type=submit value=submit>
<input type=hidden name=txt_xml_modules id=txt_xml_modules>
</form>
</body>
</html> 22
Scenario 1 Explained
(Create XML Document)
• Step 1: An XML string with only the root is
created.
var xml_modules= "<modules></modules>";

• Step 2: This XML string is converted into an


XML document.
var xmlDoc_modules = loadXMLString(xml_modules);

23
Scenario 1 Explained
(loadXMLString function)
function loadXMLString(txt)
{
var xmlDoc;

try //Internet Explorer


{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";
xmlDoc.loadXML(txt);
//xmlDoc.encoding="UTF-8";
return xmlDoc;
}
catch(e)
{
try //Firefox, Mozilla, Opera, etc.
{
parser=new DOMParser();
xmlDoc=parser.parseFromString(txt,"text/xml");
xmlDoc.encoding="UTF-8";
return xmlDoc;
}
catch(e) {alert(e.message)}
}
return(null);
}//end function loadXMLString 24
Scenario 1 Explained
(addTableRow function)
• Step 3: Data is added to the XML by calling
addTableRow( ) which in turn calls insertModule( )
function addTableRow()
{
var modulecode=document.forms[0].txt_modulecode.value;
var moduledesc = document.forms[0].txt_moduledesc.value;

insertModule(modulecode, moduledesc);

//Now clear the fields


document.forms[0].txt_modulecode.value="";
document.forms[0].txt_moduledesc.value="";
//recompute display
displayItems()
return false; //to prevent the data from being submitted to the server
}//end function addtablerow()
25
Scenario 1 Explained
(insertModule function)
function insertModule(modulecode, moduledesc)
{
modules_node=xmlDoc_modules.childNodes[0]; //Get reference to root

//create the new empty node


module_node = xmlDoc_modules.createElement("module");
modulecode_node =xmlDoc_modules.createElement("modulecode");
moduledesc_node =xmlDoc_modules.createElement("moduledesc");
module_node.appendChild(modulecode_node); <modules>
module_node.appendChild(moduledesc_node);
modules_node.appendChild(module_node);
<module>
<modulecode>
//fill in the empty nodes
modulecode_node_val = xmlDoc_modules.createTextNode(modulecode);
modulecode_node.appendChild(modulecode_node_val); modulecode variable
passed as parameter
moduledesc_node_val = xmlDoc_modules.createTextNode(moduledesc);
moduledesc_node.appendChild(moduledesc_node_val); moduledesc variable
return true; passed as parameter
}//end insertModule
26
Scenario 1 Explained
(displayItems function)
function displayItems()
{
table_str= "Modules Processed <br/><table border=1>";
modules_div = document.getElementById("div_modules");
modules_node=xmlDoc_modules.childNodes[0];
len = modules_node.childNodes.length;

for (i=0; i<len ;i++)


{
table_str = table_str + "<tr><td width=200>";
module_code = modules_node.childNodes[i].childNodes[0].firstChild.nodeValue;
table_str = table_str + module_code +"</td><td width=200>";
module_desc = modules_node.childNodes[i].childNodes[1].firstChild.nodeValue;
table_str = table_str + module_desc +"</td></tr>";
}
table_str = table_str + "</table>";
modules_div.innerHTML = table_str;
}//end function displayItems()
27
Scenario 1 Explained
(displayItems function - XML Tree Nodes)
<modules> modules_node
<module> childNodes[0]
<modulecode> childNodes[0]
CSE2041 firstChild.nodevalue OR childNodes[0].nodevalue
</modulecode>
<moduledesc> childNodes[1]
Web Tech II firstChild.value OR childNodes[0].nodevalue
</moduledesc>

<module>

<module> childNodes[1]
<modulecode> childNodes[0]
CSE1041 firstChild.nodevalue OR childNodes[0].nodevalue
</modulecode>
<moduledesc> childNodes[1]
Web Tech 1 firstChild.value OR childNodes[0].nodevalue
</moduledesc>
</module>
</modules> 28
Scenario 1 Explained
(encodeItems & getBrowser functions)
function getBrowser()
function encodeItems()
{
{
var sbrowser=navigator.userAgent;
var browser=getBrowser();
if (sbrowser.toLowerCase().indexOf('msie')>-1)
var xmlstring;
return "ie";
if (browser=="ie")
if (sbrowser.toLowerCase().indexOf('firefox')>-
{
1)
xmlstring=xmlDoc_modules.xml;
return "ff";
alert(xmlstring);
return "";
document.forms[0].txt_xml_modules.value= xmlstring;
}//end function getBrowser()
return true;
}
if (browser=="ff")
{
xmlstring = (new
Refer to addmodule_xml.html
XMLSerializer()).serializeToString(xmlDoc_modules); for the complete set of
document.forms[0].txt_xml_modules.value= xmlstring; JavaScript codes.
alert(xmlstring);
return true;
}

return false;
}//end function encode_Items()
29
XML DOM and JavaScript
• Scenario 2:
– Allow the user to delete nodes from the XML.
document, thus re-computing the display.
– The delete button is added for each row and the
deleteNode parameter corresponds to the
appropriate module node in the XML document.
<button id="+i+" onclick=deleteNode(this)>Delete</button>
– On clicking on the delete Button, the deleteNode()
function is invoked.
• A reference is created to the appropriate node and the latter
deleted using removeChild().
• Refer to addmodule_xmldelete.html for the complete set of
codes. 30
XML DOM and JavaScript
• Scenario 3:
– Allowing the user to choose an entry and update it.
– Use a global variable global_update_mode to keep track of
whether we are in insert or update mode.
– Codes that add a button next to each row:
<button id="+i+" onclick='return
retrieveNode(this)'>Update</button>
– retrieveNode() sets the update mode, gets the appropriate
values and places them in the text fields.
– updateModule() changes the appropriate node values to
the new values and changes the update mode to false.
• Refer to addmodule_xmldeleteupdate.html for the
complete set of codes. 31
References
• Adapted from XML, XSD and XSLT in Action
with PHP and JavaScript Part 1 & 2, by Mr
Anwar Chutoo.

32

You might also like