PHP traversal parses XML into an array implementation method

Source: Internet
Author: User
Tags xpath
Public function parsexml ($ menus ){
2 $ result = array ();
3 foreach ($ menus as $ menu ){
4 $ tmparr = array ();
5
6 // process empty text node method
7 if ($ menu-> nodename! = '# Text '){
8
9 // skip the text node when retrieving child elements-Method B for processing empty text nodes
10 for ($ I = 1; $ I <$ menu-> childnodes-> length; $ I + = 2 ){
11 $ anode = $ menu-> childnodes-> item ($ I );
12
13 // subelement traversal
14 $ anode-> childnodes-> length> 1? $ Tmparr [$ anode-> nodename] = $ this-> parsexml ($ anode-> childnodes)
15: $ tmparr [$ anode-> nodename] = $ anode-> nodevalue;
16}
17 array_push ($ result, $ tmparr );
18}
19}
20 return $ result;
21}
22
23
24
25 $ doc = new domdocument ();
26 $ doc-> load ('A. XML ');
27
28 // first, empty text node
29 $ menus = $ doc-> getelementsbytagname ('sitemap')-> item (0)-> childnodes;
30
31 // Type 2: specify the tag, and the sequence does not contain empty text nodes. But the child element is still empty.
32
33 $ xpath = new domxpath ($ doc );
34 $ query = "/sitemap/child: ";
35
36 $ menus = $ xpath-> query ($ query );

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.