trying to parse xml

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View

    I'm trying to parse an xml file into an array tree.  From the PHP site  
in the comments, I got this code.  But it doesn't work for me.  It's saying  
that the passed variable is not an array or object in the call end($stack),  
in the first function startElement().  Anyone know why that would be?  
$stack is an array, as far as I can tell.



$file = "data.xml";
$depth = 0;
$tree = array();
$tree['name'] = "root";
$stack[] = &$tree;

function startElement($parser, $name, $attrs) {
   global $depth;
   global $stack;
   global $tree;

   $element = array();
   foreach ($attrs as $key => $value) {

   $stack[key($stack)][strtolower($name)] = &$element;
   $stack[strtolower($name)] = &$element;


function endElement($parser, $name) {
   global $depth;
   global $stack;


$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",
$tree = end(end($stack));
echo "<pre>";
echo "</pre>";


Re: trying to parse xml

Quoted text here. Click to load it

maybe its just me, but where is this function "end" set up?

Re: trying to parse xml

end is a php function, it points the current position of an array to its  

Re: trying to parse xml

Bint wrote:

Quoted text here. Click to load it

Not the most elegant code, but it seems to work here using PHP 5.2.5.  
Which version of PHP are you using?

Toby A Inkster BSc (Hons) ARCS
[Geek of HTML/SQL/Perl/PHP/Python/Apache/Linux]
[OS: Linux, up 12 days, 20:32.]

                      Sharing Music with Apple iTunes

Site Timeline