Interpret the role of PHPDOMDocument in parsing XML files. When using the XML file used, we also take the simplexml method for php xml processing as an example. the file name is me. xml. The code is as follows: how does PHPXML process XML code? Xmlversi in use
The XML file used is also named "simple Xml for Php XML processing". the file name is me. xml. The code is as follows:
Php xml Processing XML code
- <? Xml version = "1.0" encoding = "UTF-8"?>
- <Phplamp>
- <Post>
- <Title id = "1"> php xml Processing Overview 1 </title>
- <Details> details 1 </details>
- </Post>
- <Post>
- <Title id = "2"> php xml processing Introduction 2 </title>
- <Details> details 2 </details>
- </Post>
- <Post>
- <Title id = "3"> php xml processing Introduction 3 </title>
- <Details> details 3 </details>
- </Post>
- </Phplamp>
Then, you need to use PHP DOMDocument to process the file and parse all the elements in the XML file. The code is as follows, which contains comments.
PHP DOMDocument parse XML file code
- <? Php
- // Create a DOMDocument object first
- $ Xml = new DOMDocument ();
-
- // Load the Xml file
- $ Xml-> load ("me. xml ");
-
- // Obtain all post tags
- $ PostDom = $ xml->
GetElementsByTagName ("post ");
-
- // Cyclically traverse the post tag
- Foreach ($ postDom as $ post ){
- // Obtain the Title label Node
- $ Title = $ post->
GetElementsByTagName ("title ");
-
- /**
- * The Id attribute of the Title tag to be obtained must be divided into two parts.
- * 1. obtain all attributes of the title
The list is $ title-> item (0)-> attributes
- * 2. obtain the attributes of the id in the title,
Because it is in the first place, item (0) is used)
- *
- * Tips:
- * If you take the attribute value, you can use item (*)-> nodeValue
- * If an attribute tag is used, you can use item (*)-> nodeName
- * If the attribute type is used, you can use item (*)-> nodeType
- */
- Echo "Id:". $ title-> item (0)->
Attributes-> item (0)-> nodeValue. "<br/> ";
- Echo "Title:". $ title->
Item (0)-> nodeValue. "<br/> ";
- Echo "Details:". $ post->
GetElementsByTagName ("details")-> I
Tem (0)-> nodeValue. "<br/> ";
- }
- ?>
This is only one method. PHP DOMDocument is quite powerful and there are more parsing methods and strategies to be explored.
In addition, the XML file used by idea takes simplexml for Php Xml processing as an example. the file name is me. XML. The code is as follows: php xml Processing XML code? Xml versi...