php and the dom there was some experimental support for the dom in php 4 but it is only with php 5...
Post on 19-Dec-2015
213 views
TRANSCRIPT
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/…/…/...
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
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
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
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
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
Example PHP program
• Suppose we have an XML file which contains<?xml version="1.0"?>
<companies>
<company>Toyota</ company >
< company >Honda</ company >
< company >Ford</ company >
</companies>
• 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
<?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 "<html>";
echo "<body>";
$num= $doc->getElementsByTagName("company")->length;
echo ”There are $num company elements in the file";
echo "</body>";
echo "</html>";
?>
The PHP DOMDocument class
• Extends DOMNode
• Methods createAttribute() - Create new attribute createAttributeNS() - Create new attribute node with an associated
namespace createCDATASection() - Create new cdata node createComment() - Create new comment node createDocumentFragment() - Create new document fragment createElement() - Create new element node createElementNS() - Create new element node with an associated
namespace createEntityReference() - Create new entity reference node createProcessingInstruction() - Creates new PI node createTextNode() - Create new text node
The PHP DOMDocument class contd.• getElementById() - Searches for an element with a certain id
getElementsByTagName() - Searches for all elements with given tag name getElementsByTagNameNS() - Searches for all elements with given tag
name in specified namespace importNode() - Import node into current document load() - Load XML from a file loadHTML() - Load HTML from a string loadHTMLFile() - Load HTML from a file loadXML() - Load XML from a string normalize() - Normalizes document relaxNGValidate() - Performs relaxNG validation on the document relaxNGValidateSource() - Performs relaxNG validation on the document
The PHP DOMDocument class contd.• save() - Dumps the internal XML tree back into a file
saveHTML() - Dumps the internal document into a string using HTML formatting
saveHTMLFile() - Dumps the internal document back into a file using HTML formatting
saveXML() - Dumps the internal XML tree back into a string schemaValidate() - Validates a document based on a schema schemaValidateSource() - Validates a document based on a schema validate() - Validates the document based on its DTD xinclude() - Substitutes XIncludes in a DOMDocument Object
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
The PHP DOMDocument class contd.
• Attributes (contd.)validateOnParse bool
version string
xmlEncoding string
xmlStandalone bool
xmlVersion string
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
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
Example of XML-based data exchange (contd.)
• ABC and XYZ agree on the following DTD for XML documents which describe their suppliers<!ELEMENT supplier (suppliers+) >
<!ELEMENT supplier (vatNumber,name) >
<!ELEMENT vatNumber (#PCDATA) >
<!ELEMENT name (#PCDATA) >
• 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
ABC’s XML-generation program<?php
header('Content-Type: application/xml');
echo '<?xml version="1.0"?>';
echo '<suppliers>';
$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"];
?> <supplier>
<vatNumber><?php echo $companyID; ?></vatNumber>
<name><?php echo $companyName; ?></name>
</supplier> <?php
}
echo '</suppliers>';
?>
ABC’s XML-input program
<?php$url = $_POST['url'];
if (!$url)
{?>
<h1>Supplier data acquisition</h1>
<form method="post" action="<?php echo $PHP_SELF;?>">
URL of XML file: <input type=text name=url size=60>
<button type=submit>Submit</button>
</form>
<?php
}
else
{
Code is on next slide }
?>
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);
}
?>
XYZ’s XML-generation program<?php
header('Content-Type: application/xml');
echo '<?xml version="1.0"?>';
echo '<suppliers>';
$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"];
?> <supplier>
<vatNumber><?php echo $vatNumber; ?></vatNumber>
<name><?php echo $name; ?></name>
</supplier> <?php
}
echo '</suppliers>';
?>
XYZ’s XML-input program
<?php$url = $_POST['url'];
if (!$url)
{?>
<h1>Supplier data acquisition</h1>
<form method="post" action="<?php echo $PHP_SELF;?>">
URL of XML file: <input type=text name=url size=60>
<button type=submit>Submit</button>
</form>
<?php
}
else
{
Code is on next slide }
?>
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);
}
?>