Home  >  Article  >  Backend Development  >  PHP traverses and parses XML into an array implementation code

PHP traverses and parses XML into an array implementation code

WBOY
WBOYOriginal
2016-07-25 08:58:49856browse
  1. /**
  2. * Traverse and parse the xml file into an array
  3. * edit bbs.it-home.org
  4. */
  5. public function parseXML($menus){
  6. $result = array();
  7. foreach($menus as $menu){
  8. $tmparr = array ();
  9. //How to handle empty text nodes A
  10. if( $menu->nodeName !='#text'){
  11. // Skip over text nodes when retrieving child elements - Method B
  12. for handling empty text nodes for($i=1; $i<$menu->childNodes->length; $i+=2) {
  13. $aNode = $menu->childNodes->item($i);
  14. // Child element traversal
  15. $aNode->childNodes->length > 1 ? $tmparr[$aNode->nodeName] = $this->parseXML( $aNode->childNodes)
  16. : $tmparr[$aNode ->nodeName] = $aNode->nodeValue;
  17. }
  18. array_push($result,$tmparr);
  19. }
  20. }
  21. return $result;
  22. }
  23. $doc = new DOMDocument();
  24. $doc-> ;load ( 'a.xml' );
  25. //The first type, with empty text nodes
  26. $menus = $doc->getElementsByTagName('siteMap')->item(0)->childNodes;
  27. //The second type, clearly specify the label, and the sequence has no empty text nodes. But the child element still has empty nodes
  28. $xpath = new DOMXPath($doc);
  29. $query = "/siteMap/child::a";
  30. $menus = $xpath->query($query);
  31. ? >
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.



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn