Presentation is loading. Please wait.

Presentation is loading. Please wait.

PHP and the DOM There was some experimental support for the DOM in PHP 4 But it is only with PHP 5 that support appears to have stabilized At present,

Similar presentations


Presentation on theme: "PHP and the DOM There was some experimental support for the DOM in PHP 4 But it is only with PHP 5 that support appears to have stabilized At present,"— Presentation transcript:

1 PHP and the DOM There was some experimental support for the DOM in PHP 4 But it is only with PHP 5 that support appears to have stabilized At present, the main Apache server on cosmos.ucc.ie supports only PHP 4 A second Apache server, which supports PHP 5 has just been installed on cosmos –it listens to port 8949 instead of port 80 –thus, URLs must be of the form http://cosmos.ucc.ie:8949/…/…/...

2 DOM support in PHP 5 The DOM library in PHP 5 is documented in Chapter XXX of the manual for PHP 5 –The relevant chapter is available online at http://www.php.net/manual/en/ref.dom.php DOM support in PHP 5 is object-oriented You may find other people using older PHP functions which were not object- oriented –you should avoid using those functions

3 DOM support in PHP 5 DOM support in PHP 5 follows the W3C DOM Level 2 standard quite closely –although some Level 3 aspects are included This is one reason why DOM support in PHP 5 is fully object-oriented. It is a good idea, when using DOM support in PHP 5, to cross-refer to the W3C DOM standard DOM support in PHP 5 comprises a set of object classes. –These PHP object classes correspond closely (sometimes exactly) to classes in the DOM standard –Consider some W3C DOM class xxx the corresponding PHP class has a name of the form DOMxxx –for example the class NodeList in W3C DOM has a corresponding class in PHP called DOMNodeList

4 Example W3C and PHP comparison: the NodeList class In the W3C DOM Level 1, Level 2 and Level 3 specifications, the NodeList class has –only one method item –and one attribute: length The object class DOMNodeList in the PHP DOM library corresponds to this exactly. There is – one method: item –and one attribute: length

5 Another W3C and PHP comparison In the W3C DOM Level 1 specification, there were six methods for the Node class: insertBefore replaceChild removeChild appendChild hasChildNodes cloneNode The W3C DOM Level 2 specification added three extra methods for the Node class: hasAttributes isSupported normalize The PHP DOMNode class has twelve methods: insertBefore replaceChild removeChild appendChild hasChildNodes cloneNode hasAttributes isSupported normalize lookupNameSpaceURI lookupPrefix isSameNode The last three methods in the PHP DOM library correspond to some of the nine extra methods introduced in DOM Level 3

6 Another W3C and PHP comparison contd. In the W3C DOM Level 1 specification, there were eleven attributes for the Node class: nodeType nodeName nodeValue parentNode childNodes firstChild lastChild previousSibling nextSibling attributes ownerDocument The W3C DOM Level 2 specification added three extra attributes for the Node class: namespaceURI prefix localName The W3C DOM Level 3 specification added two extra attributes for the Node class: baseURI textContent All these attributes are supported in the PHP DOMNode class, which provides sixteen attributes: nodeType nodeName nodeValue parentNode childNodes firstChild lastChild previousSibling nextSibling attributes ownerDocument namespaceURI prefix localName baseURI textContent

7 Example PHP program Suppose we have an XML file which contains Toyota Honda Ford Suppose its URL is http://www.abc.com/partners/suppliers.xml Suppose we want to write a PHP program which will count the number of company elements that are in this file A program to do this is on the next slide

8 <?php $string = file_get_contents(‘http://www.abc.com/partners/suppliers.xml’); $doc = new DOMDocument(); $doc->loadXML($string); // parses string into a document object model echo " "; $num= $doc->getElementsByTagName("company")->length; echo ”There are $num company elements in the file"; echo " "; ?>

9 Output from previous program Note the URL uses port number 8949

10 The PHP DOMDocument class Extends DOMNode Methods  createAttribute() - Create new attribute createAttribute()  createAttributeNS() - Create new attribute node with an associated namespace createAttributeNS()  createCDATASection() - Create new cdata node createCDATASection()  createComment() - Create new comment node createComment()  createDocumentFragment() - Create new document fragment createDocumentFragment()  createElement() - Create new element node createElement()  createElementNS() - Create new element node with an associated namespace createElementNS()  createEntityReference() - Create new entity reference node createEntityReference()  createProcessingInstruction() - Creates new PI node createProcessingInstruction()  createTextNode() - Create new text node createTextNode()

11 The PHP DOMDocument class contd. getElementById() - Searches for an element with a certain idgetElementById()  getElementsByTagName() - Searches for all elements with given tag name  getElementsByTagNameNS() - Searches for all elements with given tag name in specified namespace getElementsByTagNameNS()  importNode() - Import node into current document importNode()  load() - Load XML from a file  loadHTML() - Load HTML from a string loadHTML()  loadHTMLFile() - Load HTML from a file loadHTMLFile()  loadXML() - Load XML from a string  normalize() - Normalizes document normalize()  relaxNGValidate() - Performs relaxNG validation on the document relaxNGValidate()  relaxNGValidateSource() - Performs relaxNG validation on the document relaxNGValidateSource()

12 The PHP DOMDocument class contd. save() - Dumps the internal XML tree back into a filesave()  saveHTML() - Dumps the internal document into a string using HTML formatting saveHTML()  saveHTMLFile() - Dumps the internal document back into a file using HTML formatting saveHTMLFile()  saveXML() - Dumps the internal XML tree back into a string saveXML()  schemaValidate() - Validates a document based on a schema schemaValidate()  schemaValidateSource() - Validates a document based on a schema schemaValidateSource()  validate() - Validates the document based on its DTD validate()  xinclude() - Substitutes XIncludes in a DOMDocument Object xinclude()

13 The PHP DOMDocument class contd. Attributes (name followed by type) actualEncoding string config DOMConfiguration doctype DOMDocumentType documentElement DOMElement documentURI string encoding string formatOutput bool implementation DOMImplementation preserveWhiteSpace bool recover bool resolveExternals bool standalone bool strictErrorChecking bool substituteEntities bool

14 The PHP DOMDocument class contd. Attributes (contd.) validateOnParse bool version string xmlEncoding string xmlStandalone bool xmlVersion string

15 Example application of the PHP DOM library Data exchange between companies

16 Using XML for data-exchange Suppose we have 10 companies which interact with each other Suppose they all have different database formats Every company needs to be able to exchange data with every other company If we build programs to effect direct db-to-db conversions, we will need 90 different conversion programs But if we use XML as an intermediate format, we will need “only” 20 different conversion programs Put this another way: –When a company joins an “extended enterprise” which already contains N companies, if XML is used for data-exchange, the new company must write 2 conversion programs and the existing companies need do nothing if direct db-to-db conversion is used, the new company must write N conversion programs and each of the existing N companies must write one conversion program the difference is 2 programs versus 2N programs when a new company joins a group of N existing companies

17 Example of XML-based data exchange Suppose that two companies, ABC and XYZ, have decided to amalgamate They want to share data on the partner companies from whom they get their supplies ABC’s existing database, called corporate, has a table called partners with the following fields: companyVATNumber and companyName XYZ’s existing database, called mainDB, has a table called suppliers with the following fields: vatNumber and name ABC and XYZ decide to exchange data via XML

18 Example of XML-based data exchange (contd.) ABC and XYZ agree on the following DTD for XML documents which describe their suppliers Each company must write two programs: –one program to copy their database table into an XML document having the format specified above; –another program to read XML documents in the above format and insert the information into their database If they ABC-XYZ consortium later takes over any more companies, each of the new companies will have to write their own versions of the above two programs

19 ABC’s XML-generation program <?php header('Content-Type: application/xml'); echo ' '; $db=mysql_connect("localhost",”username",”password"); mysql_select_db("corporate",$db); $result=mysql_query("select * from partners",$db); while ($row=mysql_fetch_array($result)) {$companyID=$row["companyID"]; $companyName=$row["companyName"]; ?> <?php } echo ' '; ?>

20 ABC’s XML-input program <?php$url = $_POST['url']; if (!$url) {?> Supplier data acquisition "> URL of XML file: Submit <?php } else { Code is on next slide } ?>

21 ABC’s XML-input program (continued) <?php $string=file_get_contents($url); $doc= new DOMDocument(); $doc->loadXML($string); $supplierElements=$doc->getElementsByTagName("supplier"); $numSuppliers = $supplierElements->length; $db=mysql_connect("localhost","username","password"); mysql_select_db("corporate",$db); for ($i=0; $i <= $numSuppliers-1; $i=$i+1) {$supplierElement = $supplierElements->item($i); $vatNumberElement= $supplierElement->getElementsByTagName("vatNumber")->item(0); $vatNumber = $vatNumberElement->nodeValue; $nameElement= $supplierElement->getElementsByTagName("name")->item(0); $name = $nameElement->nodeValue; mysql_query("insert into partners values ($vatNumber,'$name')”,$db); } ?>

22 XYZ’s XML-generation program <?php header('Content-Type: application/xml'); echo ' '; $db=mysql_connect("localhost",”username2",”password2"); mysql_select_db("mainDB",$db); $result=mysql_query("select * from suppliers",$db); while ($row=mysql_fetch_array($result)) {$vatNumber=$row["vatNumber"]; $name=$row["name"]; ?> <?php } echo ' '; ?>

23 XYZ’s XML-input program <?php$url = $_POST['url']; if (!$url) {?> Supplier data acquisition "> URL of XML file: Submit <?php } else { Code is on next slide } ?>

24 XYZ’s XML-input program (continued) <?php $string=file_get_contents($url); $doc= new DOMDocument(); $doc->loadXML($string); $supplierElements=$doc->getElementsByTagName("supplier"); $numSuppliers = $supplierElements->length; $db=mysql_connect("localhost","username2","password2"); mysql_select_db("mainDB",$db); for ($i=0; $i <= $numSuppliers-1; $i=$i+1) {$supplierElement = $supplierElements->item($i); $vatNumberElement= $supplierElement->getElementsByTagName("vatNumber")->item(0); $vatNumber = $vatNumberElement->nodeValue; $nameElement= $supplierElement->getElementsByTagName("name")->item(0); $name = $nameElement->nodeValue; mysql_query("insert into partners values ($vatNumber,'$name')”,$db); } ?>


Download ppt "PHP and the DOM There was some experimental support for the DOM in PHP 4 But it is only with PHP 5 that support appears to have stabilized At present,"

Similar presentations


Ads by Google