You are here: trying to parse xml « PHP Programming Language « IT news, forums, messages
trying to parse xml

Posted by Bint on 12/19/07 20:06

Hi,

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.

Thanks
B


<?php

$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) {
$element[strtolower($key)]=$value;
}

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

$depth++;
}

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

array_pop($stack);
$depth--;
}

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

?>

 

Navigation:

[Reply to this message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация