Page 1 of 1

How to parse XML?

Posted: Thu Feb 26, 2009 11:45 pm
by Jan0
Hi,

I am using codigniter(Model,view,Controllers) and amfphp(flex) for my project.I am new to use codigniter and amfphp.I understood that we accept data from flex in the form of XML.So in PHP,i need a function to parse XML and store the values in the form of an array.Can anyone provide me sample code ..Thanks in advance.

Re: How to parse XML?

Posted: Fri Feb 27, 2009 12:39 am
by shyju
You can use php XML Parser functions for it . i think this sample code is very helpfull for u .

Code: Select all

 
<?php
$file = "data.xml";
$depth = array();
 
function startElement($parser, $name, $attrs) 
{
    global $depth;
    for ($i = 0; $i < $depth[$parser]; $i++) {
        echo "  ";
    }
    echo "$name\n";
    $depth[$parser]++;
}
 
function endElement($parser, $name) 
{
    global $depth;
    $depth[$parser]--;
}
 
$xml_parser = xml_parser_create();
xml_set_element_handler($xml_parser, "startElement", "endElement");
if (!($fp = fopen($file, "r"))) {
    die("could not open XML input");
}
 
while ($data = fread($fp, 4096)) {
    if (!xml_parse($xml_parser, $data, feof($fp))) {
        die(sprintf("XML error: %s at line %d",
                    xml_error_string(xml_get_error_code($xml_parser)),
                    xml_get_current_line_number($xml_parser)));
    }
}
xml_parser_free($xml_parser);
?>
 
 
Visit : http://phpwebscript.blogspot.com/

Re: How to parse XML?

Posted: Fri Feb 27, 2009 12:48 am
by John Cartwright
If you have php5 then you should consider using simplexml.

Code: Select all

 
$xml = simplexml_load_string($string);
 
var_dump($xml);