How do I return an XML element?

Discussion in 'PHP' started by bobby9101, Feb 11, 2007.

  1. #1
    I am using fopen to open an xml document.
    Say there is an element: <USER AGE="15"/>
    How do I echo that 15 in PHP?
    Do I need an XML library? was hoping there was a straight PHP way, possibly regex
     
    bobby9101, Feb 11, 2007 IP
  2. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #2
    
    
    $xml = '[...] <USER AGE="15"/> [...]';
    
    preg_match('/<user\s+age="([\d]+)"\/>/i', $xml, $match);
    
    echo $match[1];
    
    
    PHP:
    Untested but should work.
     
    nico_swd, Feb 11, 2007 IP
  3. bobby9101

    bobby9101 Peon

    Messages:
    3,292
    Likes Received:
    134
    Best Answers:
    0
    Trophy Points:
    0
    #3
    ok so if i am using: $testingxml = fopen("xmldoc.xml", "r");
    how to i integrate, sorry I am a n00b.... i just dont see how your script requires the fopen. but if not, then where is it getting the XML from?
     
    bobby9101, Feb 11, 2007 IP
  4. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #4
    I'd use file_get_contents() (Much easier to use)

    
    
    $xml = file_get_contents('xmldoc.xml');
    
    preg_match('/<user\s+age="([\d]+)"\/>/i', $xml, $match);
    
    echo $match[1];
    
    PHP:
     
    nico_swd, Feb 11, 2007 IP
  5. designcode

    designcode Well-Known Member

    Messages:
    738
    Likes Received:
    37
    Best Answers:
    0
    Trophy Points:
    118
    #5
    Got that function from PHP Manual (User Contributed Notes). Very handy and useful. Convert a string containing XML into a nested array.

    
    function xml2array ($xml_data)
    {
       // parse the XML datastring
       $xml_parser = xml_parser_create ();
       xml_parse_into_struct ($xml_parser, $xml_data, $vals, $index);
       xml_parser_free ($xml_parser);
    
       // convert the parsed data into a PHP datatype
       $params = array();
       $ptrs[0] = & $params;  
       foreach ($vals as $xml_elem) {
           $level = $xml_elem['level'] - 1;
           switch ($xml_elem['type']) {
           case 'open':
               $tag_or_id = (array_key_exists ('attributes', $xml_elem)) ? $xml_elem['attributes']['ID'] : $xml_elem['tag'];
               $ptrs[$level][$tag_or_id] = array ();
               $ptrs[$level+1] = & $ptrs[$level][$tag_or_id];
               break;
           case 'complete':
               $ptrs[$level][$xml_elem['tag']] = (isset ($xml_elem['value'])) ? $xml_elem['value'] : '';
               break;
           }
       }
       
       return ($params);
    
    } 
    PHP:
     
    designcode, Feb 12, 2007 IP