PHP DOM & XPath
Document Object Model (
DOM) is a programming API for HTML and XML documents defining the logical structure.
XPath (XML Path Language) is based on a tree representation of the XML/HTML document, and provides the ability to navigate around the tree, selecting nodes by a variety of criteria.
Document Object Model or
DOM in combination with
XPath are powerful/useful tools for screen scraping, programming and data manipulation (and much more).
Unfortunately all the features are less known, often poorly documented and with very little tutorials.
One should keep the following points in mind, while working with XPath:
- XPath is core component of XSLT standard.
- XSLT cannot work without XPath.
- XPath is basis of XQuery and XPointer.
Structuring XML and HTML
According to the W3C HTML DOM standard, everything in an HTML document is a node:
- The entire document is a document node,
- Every HTML element is an element node,
- The text inside HTML elements are text nodes,
- Every HTML attribute is an attribute node (deprecated),
- All comments are comment nodes,
The nodes in the node tree have a hierarchical relationship to each other which have to be defined clearly:
- Root : the top node of the tree,
- Parent : every node has exactly one parent except the root, which has no parent,
- Child : A node can have a number of children,
- Sibling : Siblings (brothers or sisters) are nodes with the same parent.
|From the HTML on the right you can read|
|Use the following node properties to navigate between nodes|
The nodeName property specifies the name of a node.
- nodeName is read-only
- nodeName of an element node is the same as the tag name,
- nodeName of an attribute node is the attribute name
- nodeName of a text node is always #text,
- nodeName of the document node is always #document.
The nodeValue property specifies the value of a node.
- nodeValue for element nodes is null,
- nodeValue for text nodes is the text itself,
- nodeValue for attribute nodes is the attribute value.
The nodeType property
- nodeType is read only.
- nodeType is the type of a node.
The most important nodeType properties are:
|ATTRIBUTE_NODE||2||class = "heading" (deprecated)|
|DOCUMENT_NODE||9||The HTML document itself (the parent of <html>)|
- Remark: Type 2 is deprecated in the HTML DOM (but works). It is not deprecated in the XML DOM.
- See the full list: https://www.php.net/manual/en/dom.constants.php
Tutorials on xpath made by the Website ZVON .
1 <AAA> 2 <BBB/> 3 <CCC/> 4 <BBB/> 5 <BBB/> 6 <DDD> 7 <BBB/> 8 </DDD> 9 <CCC/> 10 </AAA>
- Riptutoral, Learning XPath (XPath.pdf) is an excellent free eBook-tutorial without the XML explanations, so solely on XPath.
- devhints.io, XPath CheatSheet contains useful examples for XPath queries.
- ↑ ZVON.org, Tutorials by Example on HTML, CSS, XPath, XML, Schemas and much more.
- ↑ ZVON XPath Tutorial, XPath Tutorial by Example.
- ↑ Infocenter Sybase XPath operator and functions