PHPverse 2025

Voting

: min(six, six)?
(Example: nine)

The Note You're Voting On

rubentrancoso at gmail dot com
18 years ago
My 25 cents. This example show how to parse a XML in a associative array tree.

<?php

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

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

$element = array();
$element['name'] = $name;
foreach (
$attrs as $key => $value) {
//echo $key."=".$value;
$element[$key]=$value;
}

$last = &$stack[count($stack)-1];
$last[count($last)-1] = &$element;
$stack[count($stack)] = &$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 = $stack[0][0];
echo
"<pre>";
print_r($tree);
echo
"</pre>";

<< Back to user notes page

To Top