The DOM Extension of PHP and Scriptol
Document Object Model is a standard and a recommendation from W3C for accessing content of XML and HTML documents
- What is DOM
- Installing and using the DOM extension
- Main DOM classes and functions
- Demo of a simple DOM
Model is a universal and standard interface for accessing content of XML
and HTML documents. Functions are included also to build and modify dynamically
the structure of such documents with scripts.
DOM is a part of Ajax, and thus is essential to build modern websites or Web applications. It is used to process XML files retrieved by XMLHttpRequest and to dynamically modify the content of Web pages with the data from these files. It may be used also to create an XML document from data entered in a form and send them to the server.
The DOM interface is a part of the PHP programming language and it may be used from Scriptol PHP programs too.
Under PHP there is nothing to install: the DOM package is a part of the core
In the Scriptol source, you have just to include the header file:
DOM has classes to build or access the structure of the document (node, nodelist),
and classes to read of modify the data stored in the document (element, text).
The interface is made of these classes and methods, that are defined in the Scriptol interface:
- getElementByID() Returns the element with this ID property.
- getElementsByTagName() Returns the list of elements with this tag name.
- setAttribute() Gives an attribute to the tag.
- item(n) Returns the n th node from a nodelist created by getElementsByTagName.
Methods of DOMDocument added to PHP and not in the specification:
- loadHTMLFile() Load a file into a DOMDocument.
- save()Save the DOMDocument into an XML or a HTML file.
This very simple demo comes from the PHP manual and has been converted to Scriptol:
DOMDocument doc = DOMDocument() DOMNode root = doc.createElement('book') root = doc.appendChild(root) DOMNode title = doc.createElement('title') title = root.appendChild(title) DOMText name = doc.createTextNode('This is the title') name = title.appendChild(name) print doc.saveXML()
The goal is to create an XML document and to display it.
- The doc document is first created.
- A root node is created and appended as child of doc.
- A title node is then inserted as child of root.
- A name node is inserted as data of the title tag.
- The document is displayed by the saveXML() method.
To save if as a file, assign it to a variable and save the content of this variable into a file:
text x = doc.saveXML() file f = fopen("name.xml", "w") f.write(x) f.close()
- Download the archive of the demo (the dom.sol header
file is included).
Building the demo, type at command line:
Requirements: The PHP 4 or 5 interpreter. The Scriptol-PHP compiler.