PHP5 - Getting xml child name via PHP/DOM

Discussion in 'PHP' started by joe991, Jun 7, 2013.

  1. #1
    hi all,
    this is an extract of my big xml file.

    <doc>
    <y>
    <list_type>1</list_type>
    <libel> lible 1</libel>
     
    </y>
    <x>
    <list_type>6</list_type>
    <libel> lible 2</libel>
     
    </x>
    <y>
    <list_type>3</list_type>
    <libel> lible 3</libel>
     
    </y>
    </doc>
    Code (markup):
    <doc> is not the root of the document, its one of the root's childs, and also it's not the first child. the question here:
    how i can get the name of each child of the node <doc> using PHP/DOM?
    how i can also get all the value of each child using PHP/DOM?

    thanks
     
    joe991, Jun 7, 2013 IP
  2. gvre

    gvre Member

    Messages:
    35
    Likes Received:
    6
    Best Answers:
    3
    Trophy Points:
    33
    #2
    You could use a dom parser or something like the following, if regexp is an option:

    $pattern = '#<doc>\s*<([a-z]+)>\s*<list_type>(\d+)</list_type>\s*<libel>([^<]+)</libel>\s*</[a-z]+>\s*<([a-z]+)>\s*<list_type>(\d+)</list_type>\s*<libel>([^<]+)</libel>\s*</[a-z]+>\s*\s*<([a-z]+)>\s*<list_type>(\d+)</list_type>\s*<libel>([^<]+)</libel>\s*</[a-z]+>\s*</doc>#si';
    if (preg_match_all($pattern, $xml, $matches, PREG_SET_ORDER))
    {
            foreach($matches as $m)
            {
                    $childName1 = $m[1];
                    $listType1  = $m[2];
                    $libel1     = $m[3];
     
                    $childName2 = $m[4];
                    $listType2  = $m[5];
                    $libel2     = $m[6];
     
                    $childName3 = $m[7];
                    $listType3  = $m[8];
                    $libel3     = $m[9];
            }
    }
    
    PHP:
     
    gvre, Jun 7, 2013 IP
  3. blueparukia

    blueparukia Well-Known Member

    Messages:
    1,564
    Likes Received:
    71
    Best Answers:
    7
    Trophy Points:
    160
    #3
    blueparukia, Jun 7, 2013 IP