Pyh.conf’25: a new PHP conference for the Russian-speaking community

Voting

: min(one, five)?
(Example: nine)

The Note You're Voting On

jart (at) mail.ru
14 years ago
Guys, I hope this example will help
you can erase prints showing the process-
and it will be a piece of nice code.

<?php
function xml2assoc($xml, $name)
{
print
"<ul>";

$tree = null;
print(
"I'm inside " . $name . "<br>");

while(
$xml->read())
{
if(
$xml->nodeType == XMLReader::END_ELEMENT)
{
print
"</ul>";
return
$tree;
}

else if(
$xml->nodeType == XMLReader::ELEMENT)
{
$node = array();

print(
"Adding " . $xml->name ."<br>");
$node['tag'] = $xml->name;

if(
$xml->hasAttributes)
{
$attributes = array();
while(
$xml->moveToNextAttribute())
{
print(
"Adding attr " . $xml->name ." = " . $xml->value . "<br>");
$attributes[$xml->name] = $xml->value;
}
$node['attr'] = $attributes;
}

if(!
$xml->isEmptyElement)
{
$childs = xml2assoc($xml, $node['tag']);
$node['childs'] = $childs;
}

print(
$node['tag'] . " added <br>");
$tree[] = $node;
}

else if(
$xml->nodeType == XMLReader::TEXT)
{
$node = array();
$node['text'] = $xml->value;
$tree[] = $node;
print
"text added = " . $node['text'] . "<br>";
}
}

print
"returning " . count($tree) . " childs<br>";
print
"</ul>";

return
$tree;
}

echo
"<PRE>";

$xml = new XMLReader();
$xml->open('test.xml');
$assoc = xml2assoc($xml, "root");
$xml->close();

print_r($assoc);
echo
"</PRE>";

?>

It reads this xml:

<test>
<hallo volume="loud"> me <br/> lala </hallo>
<hallo> me </hallo>
</test>

<< Back to user notes page

To Top