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.