Presentation is loading. Please wait.

Presentation is loading. Please wait.

Server-Side Application and Data Management IT IS 3105 (Spring 2010)

Similar presentations


Presentation on theme: "Server-Side Application and Data Management IT IS 3105 (Spring 2010)"— Presentation transcript:

1 Server-Side Application and Data Management IT IS 3105 (Spring 2010)
Class 27

2 XML and PHP

3 Working with XML The name XML comes from the full name of the language, Extensible Markup Language. XML is a method of data exchange, in that it holds well-defined content within its boundaries. XML Separates Data from HTML XML Simplifies Data Sharing XML Simplifies Data Transport XML Simplifies Platform Changes

4 <root> <child id=“1”> <subchild>
<root> <child id=“1”> <subchild>.....</subchild> </child> <child id=“2”> </root>

5 XML Structure XML documents contain three major elements: the prolog, the body and the epilog The prolog contains the XML declaration statement and any processing instructions and comments you want to add. The body contains the content structure is contained The epilog contains post processing instructions Only the body is mandatory

6 XML Structure (example.xml)
<?xml version="1.0" ?> <!-- Sample XML document --> <Books> <Book id=‘1’> <Author> Vikram Vaswani </Author> <Title> PHP A Beginner’s Guide </Title> <Edition> 1</Edition> <Year> 2009 </Year> <ISBN> </ISBN> </Book> </Books>

7 XML Structure There is exactly one root element in an XML document
In the previous example the root element is Books. All subsequent elements are referred to as children elements XML Attributes provide additional information about elements XML Attribute Values Must be Quoted XML is case sensitive, so <Book> and <book> are different elements All XML tags must be properly closed XML tags must be properly nested No overlapping tags are allowed

8 Well Formed XML A "Well Formed" XML document has correct XML syntax.
The syntax rules: XML documents must have a root element XML elements must have a closing tag XML tags are case sensitive XML elements must be properly nested XML attribute values must be quoted

9 XML Parsing Methods Simple API for XML (SAX) parser:
Traverses an XML document sequentially From beginning to end Calls specific user-defined functions as it encounters different types of XML constructs Document Object Model (DOM) parser: Reads the entire XML document in one step Converts it to a hierarchical “tree” structure in memory Parser can then be programmed to traverse the tree Jumps between “sibling” or “child” branches of the tree to access specific pieces of information

10 SAX and DOM SAX reads XML data in “chunks” and is efficient for large files But requires the programmer to create customized functions to handle the different elements in an XML file DOM requires less customization But can rapidly consume memory for its actions and so is often unsuitable for large XML data files Choice of method thus depends heavily on the requirements of the application in question

11 Using the SimpleXML PHP Extension
PHP supports both SAX and DOM parsing SimpleXML extension provides a user-friendly and intuitive interface to read and process XML data SimpleXML represents every XML document as an object and turns the elements within it into a hierarchical set of objects and object properties Accessing a particular element now becomes as simple as using parent->child notation to traverse the object tree until that element is reached

12 simplexml_load_file syntax
object simplexml_load_file ( string $filename [, string $class_name = "SimpleXMLElement" [, int $options = 0 [, string $ns [, bool $is_prefix = false ]]]] ) Parameters filename path the the xml file to be parsed class_name return an object of the specified class Use “SimpleXMLElement” options ns is_prefix Returns Parsed xml object as a class of SimpleXMLExample FALSE if error

13 XML Tree Structure address street county city name zip country
<?xml version='1.0'?> <address> <street>13 High Street</street> <county>Oxfordshire</county> <city> <name>Oxford</name> <zip>OX1 1BA</zip> </city> <country>UK</country> </address> address street county city name zip country

14 SimpleXML: Reading XML Tree
address street county city name zip country <?php $xml = simplexml_load_file('address.xml') or die (“Cant load XML!"); echo "City: " . $xml->city->name . "\n"; echo "Postal code: " . $xml->city->zip . "\n"; ?> address.php

15 SimpleXML: Accessing Elements
Accessing elements within an XML document that contain characters not permitted under PHP's naming convention (e.g. the hyphen) can be accomplished by encapsulating the element name within braces and the apostrophe. <?xml version='1.0'?> <activity> <name> Business Meeting </name> <start-date>Mon, 21 Sep :30:00 EDT</start-date> <end-date>Mon, 21 Sep :30:00 EDT</end-date> </activity> <?php $xml = simplexml_load_file('activity.xml') or die (“Cant load XML!"); echo “Name: " . $xml->name . "\n"; echo “Start Date: " . $xml->{‘start-date’} . “<br>"; echo “End Date: " . $xml->{‘end-date’} . “<br>"; ?> activity.php

16 SimpleXML: Multiple element instances
library book title author year Multiple instances of the same element at the same level of the XML document tree are represented as arrays. Can easily be presented by the loops.

17 SimpleXML: Multiple element instances
library book title author year <?php $xml = simplexml_load_file(‘library.xml') or die (“Cant load XML!"); foreach ($xml->book as $book) { echo $book->title . “ is written by “ . $book->author . “<br>”; } ?>

18 SimpleXML: Counting multiple Elements
Use the count() function: <?php $xml = simplexml_load_file(‘library.xml') or die (“Cant load XML!"); echo count($xml->book) . ‘ book(s) found <br>’; ?> count.php

19 SimpleXML: Reading Attributes
SimpleXML has an easy way to get to the attributes attributes and values are converted into keys and values of a PHP associative array and can be accessed like regular array elements.

20 SimpleXML: Reading Attributes
<?xml version="1.0"?> <library> <book id="1" genre="horror" rating="5"> <title>The Shining</title> <author>Stephen King</author> <pages>673</pages> </book> … </library> <?php $xml = simplexml_load_file(‘library.xml') or die (“Cant load XML!"); foreach ($xml->book as $book) { echo $book->title . “ is written by “ . $book->author . “ genre is ”. $book[‘genre’] . “ and rating is “ . $book[‘rating’] . ”<br>”; } ?> library.php

21 Reading RSS Files rss channel title link pubDate ttl item description

22 Converting XML to SQL In some cases you need to convert an XML document to an SQL table. The steps: Read the different XML elements/attributes Store the read values into the SQL table.

23 Converting XML to SQL (Cont.)
library book title author pages <library> <book id="1" genre="horror" rating="5"> <title>The Shining</title> <author>Stephen King</author> <pages>673</pages> </book> <book id="2" genre="suspense" rating="4"> <title>Shutter Island</title> <author>Dennis Lehane</author> <pages>390</pages> </library> id genre rating title author pages 1 horror 5 The Shining Stephen King 673 2 suspense 4 Shutter Island Dennis Lehane 390

24 Converting XML to SQL (Cont.)
library book title author pages <?php $xml = simplexml_load_file(‘library.xml') or die (“Cant load XML!"); foreach ($xml->book as $book) { $query = “INSERT INTO library (id, genre, rating, title, author, pages) VALUES (‘$book[‘id’]’,’$book[‘genre’]’,’$book[‘rating’]’, ’$book->title’,’$book->author’,’$book->pages’)”; }?>

25 Altering Element and Attributes
To alter an elements and attributes: <?php $xml = simplexml_load_file(‘library.xml') or die (“Cant load XML!"); $xml->book[1]->title = ‘Invisible Prey’; $xml->book[1]->author = ‘John Sandford’; $xml->book[1]{‘rating’} = 5; header(‘Content-Type: text/xml’); echo $xml->asXML(); ?> view library2.xml alter.php

26 Adding New Elements and Attributes
Use the simplexml method addChild() to add an element Use the simplexml method addAttribute() to add an attribute <?php $xml = simplexml_load_file(‘library.xml') or die (“Cant load XML!"); $book = $xml->addChild(‘book’); $book->addAttribute(‘genre’,’travel’); $book->addAttribute(‘rating’,4); $book->addChild(‘title’, ‘Frommer Italy 2007’); $book->addChild(‘author’, ‘Various’); $book->addChild(‘pages’, 850); header(‘Content-Type: text/xml’); echo $xml->asXML(); ?> addElements.php

27 Adding the id Attribute?
Need to find the next id to give the new object: <?php $xml = simplexml_load_file(‘library.xml') or die (“Cant load XML!"); $numBooks = count($xml->book); $lastID = $xml->book[($numBooks - 1)]{‘id’}; $book = $xml->addChild(‘book’); $book->addAttribute(‘genre’,’travel’); $book->addAttribute(‘rating’,4); $book->addAttribute(‘id’,($lastID + 1)); $book->addChild(‘title’, ‘Frommer Italy 2007’); $book->addChild(‘author’, ‘Various’); $book->addChild(‘pages’, 850); header(‘Content-Type: text/xml’); echo $xml->asXML(); ?>

28 Creating New XML Documents
Can create an new empty XML document then use addChild() and addAttribute() methods. <?php $xmlStr = "<?xml version='1.0'?><person></person>"; $xml = simplexml_load_string($xmlStr); $xml->addAttribute('age', '18'); //adding attributes to person $xml->addAttribute('sex', 'male'); $xml->addChild('name', 'John Doe'); //adding child element to person $xml->addChild('dob', ' '); $address = $xml->addChild('address'); $address->addChild('street', '12 A Road'); //adding child to address $address->addChild('city', 'London'); $country = $address->addChild('country', 'United Kingdom'); $country->addAttribute('code', 'UK'); //adding attribute to address header('Content-Type: text/xml'); echo $xml->asXML(); ?> newDoc.php

29 PHP XML Review So far we covered: In this lecture:
Reading a whole XML file into an XML object Retrieving elements and attributes from an XML object. Creating a new XML object and adding elements and attributes to it. In this lecture: Querying an XML object using XPath

30 How to search in an XML? XPath:
A language for accessing different parts of an XML document, usually on the basis of specific user- defined criteria. XPath uses path expressions to select nodes or node-sets in an XML document. These path expressions look very much like the expressions you see when you work with a traditional computer file system.

31 XML Tree Structure We talked about: /addresses /addresses/address
/addresses/address/city addresses address street city name state

32 XPath Examples /A <A> <B> </B> <C> </C>
<D> </D> </A> /A/C <A> <B> </B> <C> <C> <D> </D> <C> </C> </A> /A/D/B <A> <B> </B> <C> </C> <D> <B> </B> </D> </A>

33 XPath Examples //B <A> <B></B> <C></C>
<D> </D> <C> </C> </A> //D/B <A> <B></B> <C></C> <D> </D> <C> </C> </A>

34 XPath Examples /A/C/D/* /*/*/*/B //*
      <A>           <X>                <D>                     <B><B/>                     <B><B/>                     <E><E/>                     <F><F/>                </D>           </X>           <C>                <D>                     <B><B/>                     <B><B/>                     <F><F/>                </D>           </C>           <C>                <B>                     <B>                          <B><B/>                     </B>                </B>           </C>      </A> /A/C/D/*       <A>           <X>                <D>                     <B><B/>                     <B><B/>                     <E><E/>                     <F><F/>                </D>           </X>           <C>                <D>                     <B><B/>                     <B><B/>                     <F><F/>                </D>           </C>           <C>                <B>                     <B>                          <B><B/>                     </B>                </B>           </C>      </A> /*/*/*/B       <A>           <X>                <D>                     <B><B/>                     <B><B/>                     <E><E/>                     <F><F/>                </D>           </X>           <C>                <D>                     <B><B/>                     <B><B/>                     <F><F/>                </D>           </C>           <C>                <B>                     <B>                          <B><B/>                     </B>                </B>           </C>      </A> //*

35 Xpath Examples //@id //B[@name] //B[@id] //B[@*] <A>
<B id=‘b1’> </B> <B id=‘b2’> </B> <B name=‘b3’> </B> <B> </B> </A> <A> <B id=‘b1’> </B> <B id=‘b2’> </B> <B name=‘b3’> </B> <B> </B> </A> <A> <B id=‘b1’> </B> <B id=‘b2’> </B> <B name=‘b3’> </B> <B> </B> </A> <A> <B id=‘b1’> </B> <B id=‘b2’> </B> <B name=‘b3’> </B> <B> </B> </A>

36 Xpath Examples //B[@id=‘b1’] //B[@name=‘b3’] <A> <A>
<B name=‘b3’> </B> <B> </B> </A> <A> <B id=‘b1’> </B> <B id=‘b2’> </B> <B name=‘b3’> </B> <B> </B> </A>

37 XPath Examples //C | //B /A/E | //B <A> <A>
<B> </B> <C> </C> <D> </D> <E> </E> </A> /A/E | //B <A> <B> </B> <C> </C> <D> </D> <E> </E> </A> //A/E | //D/C | /A | //B <A> <B> </B> <C> </C> <D> </D> <E> </E> </A>

38 XPath Examples //D/parent::* <A> <B> <D> <C>
<D> </D> <E> </E> </C> </D> </B> <E> <F> </F> </E> </A>

39 PHP DOM Extension Parses the entire XML document and is presented as a tree of these objects. PHP provides an OO DOM extension using DOMDocument Class: Method load(‘filename.xml’): loads an XML object childNodes: returns the an object containing a set of child

40 DOM XML: Reading XML Tree
address street county city name zip country <?php $doc = new DOMDocument(); $doc->load(‘address.xml’); // read XML file $root = $doc->firstChild; // get root element $root->childNodes->item(3)->nodeValue //gets the value country $root->childNodes->item(2)->childNodes->item(0)->nodeValue //name $root->childNodes->item(2)->childNodes->item(1)->nodeValue //zip ?>

41 DOM XML: Reading XML Tree
getElementsByTagName() is a collection of matching DOMNode objects. <?php $doc = new DOMDocument(); $doc->load('address.xml'); $country = $doc->getElementsbyTagName('country'); echo "country:" . $country->item(0)->nodeValue; echo "<br>"; $city = $doc->getElementsByTagName('name'); echo "city:" . $city->item(0)->nodeValue; $zip = $doc->getElementsByTagName('zip'); echo "zip:" . $zip->item(0)->nodeValue ; ?> domRead.php

42 XML Tree Structure domRead2.php <?php $doc = new DOMDocument();
addresses address street city name state <?php $doc = new DOMDocument(); $doc->load('addresses.xml'); $addresses = $doc->getElementsByTagName('address'); foreach ($addresses as $address) { $streetValue = $address->getElementsByTagName('street')->item(0)->nodeValue; $city = $address->getElementsByTagName('city')->item(0); $cityValue = $city->getElementsByTagName('name')->item(0)->nodeValue; $state = $address->getElementsByTagName('state')->item(0); $stateValue = $state->getElementsByTagName('name')->item(0)->nodeValue; echo "$streetValue, $cityValue, $stateValue <BR>"; } ?> domRead2.php (note data error)

43 Working with Attributes
getElementsByTagName(‘elementName‘) Retrieves nodes base on an element name getAttribute(‘attributeName’) Retrieves the attribute value with an attribute name Node->attributes Returns an array of attribute objects: attribute->name aAttribute->value

44 Challenge 1 How would one read and update an XML file?
What do need to worry about?

45 Challenge 2 How could we get data from an order form and send it to another system for further processing? Use what we have learned to now…


Download ppt "Server-Side Application and Data Management IT IS 3105 (Spring 2010)"

Similar presentations


Ads by Google