Presentation is loading. Please wait.

Presentation is loading. Please wait.

Dr James Denholm-Price XML Lecture 3 Client  Server: PHP + XML.

Similar presentations


Presentation on theme: "Dr James Denholm-Price XML Lecture 3 Client  Server: PHP + XML."— Presentation transcript:

1 Dr James Denholm-Price j.denholm-price@kingston.ac.uk XML Lecture 3 Client  Server: PHP + XML

2 Delimiters http://ars.userfriendly.org/cartoons/?id=20041025

3 Lecture 3 contents Motivation: Context & why XML. Examples: “Use cases” Client-server: Server-side processing. –Using what we know (the DOM!) –Looking forward to what we don’t yet know... –Client-side processing will be later.

4 Context “Things should be made as simple as possible, but no simpler. ” – Albert Einstein. –“Things”  CD player? To play a CD you put your CD into a CD player and the player plays it for you. The CD player provides a CD-playing service. Object oriented programming approach: –You bind data and its processing together. In O-O, every CD would come with its own player. Service-orientation approach: –Services provide functions that “do things”. –For software, services exchange data which must be comprehensible... XML is a lingua franca commonly (but not exclusively) used. Image: Albert Einstein Archives, The Hebrew University of Jerusalem, Israel.

5 Services Huge subject – “Service-Oriented Architecture” (SOA). The essence is something like: –Break down “business process” workflows. –Provide “services” using common protocols & well-defined models to securely expose “business data” –Aggregate service data into “business objects” to answer questions. –E.g. “Who’s on module CO3070 in 2010/11?” Module code  module name. Module code + year  list of student IDs. Student ID  students details. Student ID  student photo? Aggregate it all together to give a class list (e.g. PDF).

6 Why bother with “services” at all? Server HTTP DB Data Service XML Data XML Data XML Data

7 “data” direct to the client!... More later... Server HTTP DB Data Service HTTP Data HTTP Data HTTP Data

8 Why XML? Why not text? After all... –Easily read, easily written! Why not arbitrary binary files? After all... –Easily written, efficient/small size! But are they really: –Easily understood? Internationalisation! (Test: Ff vs IE)Ff vs IE Meaning! Sharing! –Easy to write?!

9 XML Written in plain text  easy to write, exchange. Defaults to UTF-8  internationalised.UTF-8 Can be defined  messages can be: –Specified. DTDs (also XML Schema, RelaxNG, Schematron...) –Validated. Can be exchanged  HTTP is easy & ubiquitous. Easy for machines to parse into data... It’s not particularly efficient (size-wise)  issue? It’s also not the only data specification with (most of) these properties... more of which in a later lecture!

10 What data’s out there? TV –http://bleb.org/tv/data/rss.php?ch=bbc1&day=0http://bleb.org/tv/data/rss.php?ch=bbc1&day=0 Youtube –http://gdata.youtube.com/feeds/base/videos?q=htc% 20desire%20hd&client=ytapi-youtube- search&alt=rss&v=2http://gdata.youtube.com/feeds/base/videos?q=htc% 20desire%20hd&client=ytapi-youtube- search&alt=rss&v=2 weather data –http://weather.yahooapis.com/forecastrss?p=UKXX07 70&u=c (Valid?)http://weather.yahooapis.com/forecastrss?p=UKXX07 70&u=cValid? Notice anything? –RSS = early example of “paving the cowpaths” ;-)RSSpaving the cowpaths

11 RSS “Rich Site Summary” or “Really Simple Syndication”... its history is complex –Wikipedia has a good summary!Wikipedia RSS v2.0 seems well-specified (DTD or XSD) if “unofficial” ;-)well-specifiedDTDXSD

12 RSS specification Human-readable versions online (e.g. RSS2)RSS2 DTD: – Etc...

13 RSS example: WebTech podcast Web Technologies Podcast http://lms.../webapps/lobj-podcast-bb_bb60/feed/CO2013-A_SEM1/podcast.xml A podcast to accompany lectures in Web Technologies... CO2013A banner.GIF http://lms.../webapps/lobj-podcast-bb_bb60/files/itunes/... Lecture 1 Introduction and revision http://staffnet.../~ku13043/WebTech/media/lecture01.mp3 Easy introduction to the module,...</a><br> Mon, 05 Oct 2009 13:37:05 GMT http://staffnet..../~ku13043/WebTech/media/lecture01.mp3 2009-10-05T13:37:05Z Valid?

14 Mashups Mash data from disparate sources into an application. Google maps is commonly used because its client-side APIs support reading & displaying data, e.g. XML data. –http://googlemapsmania.blogspot.com/http://googlemapsmania.blogspot.com/ –http://ccgi.arutherford.plus.com/website/flexTraffic/http://ccgi.arutherford.plus.com/website/flexTraffic/ UK Highways Agency Java appletUK Highways Agency –Where’s the path? OS data + Google mapsWhere’s the path? –WalkJogRun + iPhone appWalkJogRun

15 How can we process XML? Depends what we want to do with it & when: –Java application – many ways, JAXB/P is common. –Windows app’s –.Net has tools... –Web (client/server): Server-side languages (server) usually have platform- specific packages. –E.g. JSP  JAXB/P, PHP  DOM ;-) SimpleXML etc.PHPDOMSimpleXML Browsers (client) have varying support for XML, usually XMLDOM (lecture 8) & XSLT (lecture 6) –Security issues (“same origin”).

16 16 Request for remote data DNS server 1 DNS query 2 TCP connection 3 HTTP request 4 HTTP response 5 Optional parallel connections (embedded resources) Browser Origin server DB 6 Asynchronous requests Time

17 Security (1/2) Is it a good idea to let an arbitrary web page load data from any source? –No! On the client –E.g. What if you inadvertently make it possible for someone nefarious to inject arbitrary JavaScript into a page... That JavaScript could load “data” from anywhere and do anything to the page, including monitoring keystrokes, passwords, credit cards, reading cookies, phishing... –Current solution = “same origin” policy: Scripted requests must come from the same domain (web server) as the HTML.

18 Security (2/2) –“Same origin” is a severe restriction so workarounds exist ;-) E.g. a tag can do pretty-much anything; Google for “comet”. A W3C working party (on “webapps”) is looking at APIs and “trust” issues...W3C working party (on “webapps”) On the server –Strict restrictions don’t apply (but the remote server might filter requests). –Do whatever you like & get away with it badge...

19 Approaches to XML processing XPath & XSLT: after lecture ~5. –“Better” ways to navigate the node tree & manipulate data. DOM (“Document Object Model”)DOM –leverages what we know (from CO2013): Server-side and client-side. –Simple but relatively heavyweight API. –Well-defined by W3C. –Works ~OK with namespaces. Objects let us use language-native notation –Usually needs bolt-on search mechanisms, XPath... –Different in each language. –Namespaces are a mess. Other processors like SAX try to be more lightweight, particularly for large XML doc’s.

20 PHP

21 PHP is a server-side scripting language –Like ASP, JSP, ASP.Net, Cold Fusion it is executed by the server! on the server! you must preview/test your PHP from the server! Unlike CGI (Perl etc) the code is embedded within the web page –usually identified by a special extension ‘ file.php ’ not ‘ file.html ’ PHP documentation is your friend...PHP documentation –The online manual is fantastic so bookmark it! http://www.php.net/docs.php CO3041 Databases and the Web 21

22 PHP in web pages (from the PHP manual) The recommended way to embed PHP in (X)HTML is: – –You should all use this! PHP short tags are: – –These can interfere with XML instructions, like DOCTYPE or XML prolog PHP echo shortcut (like in ASP): – This is a shortcut for " " Alternative embedding to please old M$ FrontPage – echo "some editors"; Finally ASP-style could be enabled (for some mad reason!) – CO3041 Databases and the Web 22

23 A syntax quickie C-like syntax (similar to C, Java, JavaScript etc.) $ denotes a PHP variable (scalar, array, object) '....' delimits unparsed strings; "..." is parsed for variables, wrap arrays in {} $date. "; echo 'Can\'t wait until the summer ;-)'; ?>

24 Client vs Server PHP is server-side code! –The client only sees stuff that is deliberately written to the output stream. –E.g. echo, print, printf, print_r Error messages (if error_reporting is enabled.)error_reporting header(...) used to set HTTP headers (also see output buffering) output buffering

25 For now: PHP SimpleXML PHP’s SimpleXML API exposes (simple) XML documents as PHP objects E.g. – world –http://uk.php.net/manual/en/simplexml.examples -basic.phphttp://uk.php.net/manual/en/simplexml.examples -basic.php

26 RSS as XML elements

27 Introducing the document object model DOM: –Stands for Document Object Model –Developed by the W3C –Designed for XML and HTML –Interface between programming language and document content –Allows the browser to run programs to manipulate documents 27

28 W3C DOM levels Level 1:Level 1: –HTML and XML Level 2:Level 2 –Supports namespaces, Cascading Style Sheets, and user- initiated actions, such as mouse clicks and key strokes Level 3:Level 3 –Standardise support for document loading and saving –Still under development DOM spec’s exist for many XML languages & platforms –SMIL –MathML –SVG –{JavaScript, ActionScript, JScript}  ECMAScript –PHP 28

29 CO3070 XML for the Web 29 DOM nodes & tree structure W3C Level 1 Document Object Model (DOM1) –Gives access to the elements in a document –Tree structure elements correspond with nodes (objects) attributes are properties element text is a node itself –Provides methods to Query elements contents, attributes, children Add, delete, move elements within the tree Add, delete, change attributes

30 CO3070 XML for the Web 30 A simple example document Hi! Simple A bold example

31 Behind the scenes: Tree of nodes CO3070 XML for the Web 31 documentElement 'Hi!' 'Simple' 'A ' ' example' 'bold' Hi! A bold example Simple

32 Locating objects by id DOM1 $document->getElementById('theP'); –This example returns a reference to the object that represents the element in the DOM –However this only works in XML if there is an attached & valid DTD which defines an attribute of type ID. CO3070 XML for the Web 32 Hi! A bold example Simple ExampleExample (src)src NB: Examples require PHP5 XML DOM.

33 Locating objects by tag DOM1: $pEls = $document-> getElementsByTagName('p'); –Can also be called from any DOM node. –This returns a collection (~array) of objects, no prizes for guessing what's in it (not much in this simple doc!) pEls->item(…) CO3070 XML for the Web 33 Hi! A bold example Simple ExampleExample (src)src

34 Locating objects by tag #2 DOM1: $pEls = document. getElementsByTagName('p'); –pEls.item(…) –pEls.item(0) –pEls.item(1) What about “namespaces”? –getElementsByTagNameNS( namespace, tagName ) CO3070 XML for the Web 34 Hi! A bold example Ha! Simple A bold example Ha! exampleexample (src)src

35 A… e Ha! Looping over objects by tag DOM1: $pEls = $document-> getElementsByTagName('p'); for ( $i=0; $i length; $i++ ) { echo $pEls ->item($i) ->firstChild ->nodeValue; } CO3070 XML for the Web 35 Hi! A bold example Ha! Simple exampleexample (src)src

36 CO3070 XML for the Web 36 Parent node relationships If $objP == $doc->getElementById('thp'); then $objP->childNodes[] an array containing 3 nodes… $objP->firstChild the 'A ' text node $objP->lastChild the ' example' text node A bold example 'bold' 'A' ' example' children parent exampleexample (src)src

37 CO3070 XML for the Web 37 Questions: $objP->childNodes holds the children of … Q: What is $objP->childNodes->length ? Q: What does $objP->childNodes->item(1) refer to? Q: How do I access the 'bold' text node? A bold example children parent A: 3 'bold' 'A'' example' A: A: objP.childNodes[1].firstChild exampleexample (src)src

38 CO3070 XML for the Web 38 Child node relationships Each of $objP->childNodes is a set of nodes whose parentNode properties points back up the tree to the element –E.g. $objP->childNodes->item(0) is the 'A' text node $objP->childNodes->item(0)->parentNode refers back to A bold example 'A' ' example' 'bold' children parent

39 CO3070 XML for the Web 39 Question: Q: If $objP->childNodes->item(1)->firstChild is the 'bold' text node, what is: $objP->childNodes->item(1)->firstChild ->parentNode->parentNode ? A bold example 'A' ' example' 'bold' children parent A:It refers to the parent of the parent of the 'bold' text node, i.e. back to the. example example (src)src

40 CO3070 XML for the Web 40 Sibling node relationships Each of the children of the element are siblings (of each other): If $objB represents the node then –$objB == objP->childNodes->item(1) from before –$objB->nextSibling is the ' example' text node –$objB->previousSibling is the 'A' text node A bold example 'A' ' example' siblings example example (src)src

41 CO3070 XML for the Web 41 Question: Q: If $objB represents the node then what does $objB->nextSibling->parentNode refer to? A bold example 'A' ' example' siblings A:It refers back to the parent of the ' example' text node, i.e. back to the as before. (As any of the 'sibling' nodes do) parent A:

42 Node attribute methods For any DOM object $obj, use –$obj->getAttribute(attName); to query (return) an attribute value –$obj->getAttributeNS(ns,attName); to query (return) an attribute value with a namespace (ex)ex –$obj->setAttribute(attName,attValue); to set an attribute value –$obj->hasAttributes(); returns true / false CO3070 XML for the Web 42

43 Node attributes E.g.attributes of tags can be accessed from those DOM1 object methods: – –So to change the image source : $imageObj = $document.getElementById('img1'); $imageObj->setAttribute('src','image2.gif'); CO3070 XML for the Web 43

44 Node type and value properties CO2013/CO3013 XML for the Web 44 Node nodeNamenodeTypenodeValue ElementHTML tag name 1null AttributeAttribute name 2 The att. Value Text node #text3 The text CDATA #cdata- section 4 The CDATA text Comment node #comment8 The comment text Document node #document9null More: W3CW3C

45 Node type and value properties CO2013/CO3013 XML for the Web 45 Node nodeNamenodeTypenodeValue #text3'A' 'b'1null #text3' example' id="thp" ‘id'2'thp' A bold example 'A' ' example'

46 PHP XML DOM Client or server the procedure is the same: 1.Load the XML document. 2.Successfully-loaded doc is parsed into a DOM. 3.Methods & properties of the DOM objects give access to the information and relationships represented by tags. E.g. See w3schools.com, php.netw3schools.comphp.net

47 Example: Parsing RSS The example RSS document: –.................. –etc... Repeated for each –NB: What about white space?

48 XML DOM So... –$doc = new DOMDocument(); –$doc->preserveWhiteSpace=FALSE; –$doc->load('http://.../podcast.xml'); –$doc->getElementsByTagName('item'); –for ($i=0; $i length; $i++)... –$doc->item($i)->firstChild is –$doc->item($i)->childNodes->item(2) is –$doc->item($i)->childNodes->item(3) is Example


Download ppt "Dr James Denholm-Price XML Lecture 3 Client  Server: PHP + XML."

Similar presentations


Ads by Google