DOM ya PHP
- Mwanzo Page XML Expat Parser
- Pya Page XML SimpleXML
The built-in DOM parser makes it possible to process XML documents in PHP.
What is DOM?
The W3C DOM provides a standard set of objects for HTML and XML documents, as well as standard interfaces for accessing and manipulating these documents.
The W3C DOM is divided into different parts (Core, XML, and HTML) and different levels (DOM Level 1/2/3):
- Core DOM - Defines a standard set of objects for any structured document
- XML DOM - Defines a standard set of objects for XML documents
- HTML DOM - Defines a standard set of objects for HTML documents
Ikiwa unahitaji kusoma zaidi kuhusu XML DOM, tafadhali nia taarifa zetu. Makao ya XML DOM.
XML parsing
To read and update - create and process - an XML document, you need an XML parser.
There are two basic types of XML parsers:
- Tree-based parser: This parser converts the XML document into a tree structure. It analyzes the entire document and provides an API to access elements in the tree, such as the Document Object Model (DOM).
- Event-based parser: Views the XML document as a series of events. When a specific event occurs, the parser calls a function to handle it.
The DOM parser is a tree-based parser.
Please see the following XML document fragment:
<?xml version="1.0" encoding="ISO-8859-1"?> <from>John</from>
The XML DOM views XML as a tree structure:
- Level 1: XML document
- Level 2: Root element: <from>
- Level 3: Text element: "John"
Installation
The DOM XML parser is a core part of PHP. These functions can be used without installation.
XML file
The following XML file will be used in our example:
<?xml version="1.0" encoding="ISO-8859-1"?> <note> <to>George</to> <from>John</from> <heading>Reminder</heading> <body>Do not forget the meeting!</body>
Loading and outputting XML
We need to initialize the XML parser, load the XML, and output it:
例子
load("note.xml"); print $xmlDoc->saveXML(); ?>
以上代码的输出:
George John Reminder Do not forget the meeting!
If you view the source code in the browser window, you will see the following HTML:
<?xml version="1.0" encoding="ISO-8859-1"?> <note> <to>George</to> <from>John</from> <heading>Reminder</heading> <body>Do not forget the meeting!</body>
上面的例子创建了一个 DOMDocument-Object,并把 "note.xml" 中的 XML 载入这个文档对象中。
saveXML() 函数把内部 XML 文档放入一个字符串,这样我们就可以输出它。
循环 XML
我们要初始化 XML 解析器,加载 XML,并循环
例子
load("note.xml"); $x = $xmlDoc->documentElement; foreach ($x->childNodes AS $item) { print $item->nodeName . " = " . $item->nodeValue . "
"; } ?>
以上代码的输出:
#text = to = George #text = from = John #text = heading = Reminder #text = body = Don't forget the meeting! #text =
在上面的例子中,您看到了每个元素之间存在空的文本节点。
当 XML 生成时,它通常会在节点之间包含空白。XML DOM 解析器把它们当作普通的元素,如果您不注意它们,有时会产生问题。
Ikiwa unahitaji kusoma zaidi kuhusu XML DOM, tafadhali nia taarifa zetu. Makao ya XML DOM.
- Mwanzo Page XML Expat Parser
- Pya Page XML SimpleXML