-
- /**
- * Traverse and parse the xml file into an array
- * edit bbs.it-home.org
- */
- public function parseXML($menus){
- $result = array();
- foreach($menus as $menu){
- $tmparr = array ();
-
- //How to handle empty text nodes A
- if( $menu->nodeName !='#text'){
-
- // Skip over text nodes when retrieving child elements - Method B
- for handling empty text nodes for($i=1; $i<$menu->childNodes->length; $i+=2) {
- $aNode = $menu->childNodes->item($i);
-
- // Child element traversal
- $aNode->childNodes->length > 1 ? $tmparr[$aNode->nodeName] = $this->parseXML( $aNode->childNodes)
- : $tmparr[$aNode ->nodeName] = $aNode->nodeValue;
- }
- array_push($result,$tmparr);
- }
- }
- return $result;
- }
- $doc = new DOMDocument();
- $doc-> ;load ( 'a.xml' );
-
- //The first type, with empty text nodes
- $menus = $doc->getElementsByTagName('siteMap')->item(0)->childNodes;
-
- //The second type, clearly specify the label, and the sequence has no empty text nodes. But the child element still has empty nodes
-
- $xpath = new DOMXPath($doc);
- $query = "/siteMap/child::a";
- $menus = $xpath->query($query);
- ? >
Copy code
In many PHP tutorials, there is content about PHP operating xml files. Today’s code is relatively simple and easy to understand, and is suitable for reference by beginners.
Programmer's Home, I wish you all the best in your studies and progress.
|