Current location: Hot Scripts Forums » Programming Languages » PHP » Parsing XML


Parsing XML

Reply
  #1 (permalink)  
Old 02-08-06, 12:19 PM
dodotopia dodotopia is offline
Newbie Coder
 
Join Date: Apr 2005
Posts: 23
Thanks: 0
Thanked 0 Times in 0 Posts
Question Parsing XML

I am receiving the following string from another server:

PHP Code:

$xml="<r_csp></r_csp><r_time></r_time><r_ref></r_ref><r_error></r_error><r_ordernum></r_ordernum><r_message>This is a test transaction and will not show up in the Reports</r_message><r_code></r_code><r_tdate>Wed Feb 8 11:14:59 2006</r_tdate><r_score></r_score><r_authresponse></r_authresponse><r_approved>APPROVED</r_approved><r_avs></r_avs>" 

I want to be able to parse it out and get the following values put in to their respective variables:

r_avs
r_ordernum
r_error
r_approved
r_code
r_message
r_time
r_ref
r_tdate

Any pointers would be appreciated!

Thanks in advance...
Reply With Quote
  #2 (permalink)  
Old 02-08-06, 03:51 PM
Patiek Patiek is offline
Wannabe Coder
 
Join Date: Nov 2003
Posts: 165
Thanks: 0
Thanked 0 Times in 0 Posts
If the XML is always that simple, you can use this:

PHP Code:

<?php

 
$xml
="<r_csp></r_csp><r_time></r_time><r_ref></r_ref><r_error></r_error><r_ordernum></r_ordernum><r_message>This is a test transaction and will not show up in the Reports</r_message><r_code></r_code><r_tdate>Wed Feb 8 11:14:59 2006</r_tdate><r_score></r_score><r_authresponse></r_authresponse><r_approved>APPROVED</r_approved><r_avs></r_avs>";


$num_match preg_match_all("/<([^>]+)>([^<]*)<\/\\1>/is"$xml$matchesPREG_SET_ORDER);

if (
$num_match 0)
{
    
print_r($matches);
}
else
{
    echo 
"no matches";
}

?>
$matches will contain an array of an array of values.
$matches[0] will contain the first <something></something> match, $matches[1] will contain the second <somethingelse></somethingelse> match, and so on...

Within each $matches[num] is an array. For example:
$matches[0][0] would contain entire matched string.
$matches[0][1] would contain just the inner tag ("something" if <something></something>).
$matches[0][2] would contain just the inner contents ("text" if <something>text</something>).


Now, if you XML ever gets a little more complicated, you can use this class that I created (actually, there are two... but one is used by the other):
PHP Code:

<?php

// --------------------------------------------
// | EP-Dev XML Class       
// |                                           
// | Copyright (c) 2002-2006 EP-Dev.com :           
// | This program is distributed as free       
// | software under the GNU General Public     
// | License as published by the Free Software 
// | Foundation. You may freely redistribute     
// | and/or modify this program.               
// |                                           
// --------------------------------------------

/* ------------------------------------------------------------------ */
//    XML Access Class
//
//    Controls access to remote XML files. By doing this the script
//    can easily access multiple XML files.
/* ------------------------------------------------------------------ */


class EP_Dev_XML
{
    var 
$handle;
    var 
$parser;
    var 
$source;

    var 
$root;
    var 
$lastChild;


    function 
EP_Dev_XML($url)
    {
        
$this->root null;
        
$this->lastChild null;
        
$this->source $url;
    }


    function 
load()
    {
        
$this->handle fopen($this->source"r")
            or die(
"Error reading XML file: {$this->source}");
        
        
// create parser
        
$this->parser xml_parser_create();

        
// set to this object
        
xml_set_object($this->parser$this);

        
// set method handlers
        
xml_set_element_handler($this->parser"xmlStartElement""xmlEndElement");

        
// set data handler
        
xml_set_character_data_handler($this->parser"xmlElementData");
    }


    function 
parse()
    {
        while (
$data fread($this->handle4096))
        {
            
xml_parse($this->parser$datafeof($this->handle))
                or die(
                        
sprintf(
                            
"XML error ({$this->source}): %s at line %d"
                            
xml_error_stringxml_get_error_code(  $this->parser  ) ), 
                            
xml_get_current_line_number($this->parser)
                        )
                      ); 
        }

        
fclose($this->handle);
        
xml_parser_free($this->parser);
    }


    function 
getRoot()
    {
        return 
$this->root;
    }


    function 
getLastOpenChild()
    {
        
$lastChild $this->getLastChild();

        if (
$lastChild == null)
        {
            return 
null;
        }
        else
        {
            while (!
$lastChild->isOpen())
            {
                
$lastChild $lastChild->getParent();

                if (
$lastChild->isOpen() && $lastChild->getNumberChildren() > 0)
                {
                    for(
$i=0$i<$lastChild->getNumberChildren(); $i++)
                    {
                        if (
$lastChild->getChild($i+1)->isOpen())
                        {
                            
$lastChild $lastChild->getChild($i+1);
                            
$i=0;
                        }
                    }
                }
            }
        }

        return 
$lastChild;
    }


    function 
getLastChild()
    {
        return 
$this->lastChild;
    }


    function 
setLastChild(&$child)
    {
        
$this->lastChild $child;
    }


    function 
xmlStartElement($parser$tagName$attributes)
    {
        if (
$this->root == null)
        {
            
$this->root = new EP_Dev_XML_Tag($tagName$attributes$this->root);
            
$this->setLastChild($this->root);
        }
        else
        {
            
$lastOpenChild $this->getLastOpenChild();
            
$lastOpenChild->addChild( new EP_Dev_XML_Tag($tagName$attributes$lastOpenChild) );
            
$this->setLastChild$lastOpenChild->getChild$lastOpenChild->getNumberChildren() )  );
        }
    }

    function 
xmlEndElement($parser$tagName)
    {
        
$this->getLastOpenChild()->close();
    }

    function 
xmlElementData($parser$data)
    {
        
$this->getLastOpenChild()->addData($data);
    }
}


class 
EP_Dev_XML_Tag
{
    var 
$name;
    var 
$attributes;
    var 
$data;

    var 
$status;
    var 
$children;
    var 
$parent;

    var 
$childrenNames;


    function 
EP_Dev_XML_Tag($name$attributes, &$parent)
    {
        
$this->name $name;
        
$this->attributes $attributes;
        
$this->parent $parent;
        
$this->setData("");
        
$this->setOpen(true);
    }


    function 
isOpen()
    {
        return 
$this->status;
    }


    function 
open()
    {
        
$this->setOpen(true);
    }


    function 
close()
    {
        
$this->setOpen(false);
    }


    function 
addChild(&$cLink)
    {
        
$this->children[] = $cLink;

        
$this->childrenNames[$cLink->getName()] = $this->getNumberChildren();

        
// add blank data to sync children & data
        
$this->addData("");
    }


    function 
addData($data)
    {
        
// always base data off of current children number
        
$this->data[$this->getNumberChildren()] .= $data;
    }


    function 
setData($data)
    {
        unset(
$this->data);
        
$this->data[0] = $data;
    }


    function 
setOpen($openStatus)
    {
        
$this->status $openStatus;
    }


    function 
getAttributes()
    {
        return 
$this->attributes;
    }


    function 
getAttribute($attributeName)
    {
        return 
$this->attributes[$attributeName];
    }


    function 
getAttributesString()
    {
        
$attrString "";

        if (!empty(
$this->attributes))
        {
            foreach(
$this->attributes as $attribute => $value)
            {
                
$attrString .= {$attribute}=\"{$value}\"";
            }
        }

        return 
$attrString;
    }


    function 
getChildren()
    {
        return 
$this->children;
    }


    function 
getChild($child)
    {
        return 
$this->children[$child-1];
    }


    function 
getChildByName($child)
    {
        return 
$this->getChild($this->childrenNames[$child]);
    }


    function 
getData($part=0)
    {
        if (
$part != 0)
        {
            return 
$this->data[$part-1];
        }
        else
        {
            
$all_data "";

            foreach(
$this->data as $data)
            {
                
$all_data .= $data;
            }

            return 
$all_data;
        }
    }


    function 
getName()
    {
        return 
$this->name;
    }


    function 
getNumberAttributes()
    {
        return 
count($this->attributes);
    }


    function 
getNumberChildren()
    {
        return 
count($this->children);
    }


    function 
getNumberData()
    {
        return 
count($this->data);
    }


    function 
getParent()
    {
        return 
$this->parent;
    }
}
The class is bulky... so I don't recommend using it unless your XML is more complicated than what you posted.

Last edited by Patiek; 02-08-06 at 03:55 PM.
Reply With Quote
Reply

Bookmarks


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On

Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
XML parsing Arctic PHP 4 01-18-06 10:44 AM
Need XML to PHP Parsing Done angmi90 Job Offers & Assistance 1 04-28-05 01:42 PM
Shopping.com XML Feed Parsing Help Bjorn2404 Job Offers & Assistance 0 04-05-05 04:33 PM
Shopping.com XML Feed Parsing Help angmi90 PHP 4 04-04-05 06:51 PM
Advice parsing a html table to xml RossC0 JavaScript 3 03-22-05 02:10 PM


All times are GMT -5. The time now is 06:30 AM.
vBulletin® Copyright ©2000 - 2012, Jelsoft Enterprises Ltd.