Re: To get an associative array from an XML-file?
| From: | Markus Wolff | Date: | Fri, 03 Jan 2003 12:17:55 +0000 |
| Subject: | Re: To get an associative array from an XML-file? | ||
| References: | 1 2 | Groups: | php.pear.general |
| Request: | Send a blank email to pear-general+get-3165@lists.php.net to get a copy of this message | ||
On Thu, 02 Jan 2003 23:19:53 +0100
Fredrik Johansson <Fredrik@phpportalen.net> wrote:
> I want to transform:
>
> <person>
> <firstname>Fredrik</firstname>
> <lastname>Johansson</lastname>
> <person>
>
> To:
>
> $foobar['person']['firstname'] = 'Fredrik',
> $foobar['person']['lastname'] = 'Johansson'
>
> And I can't se why it's OT, if none of the PEAR-classes can do this it
> has to be implemented in one ;)
Well, as this is not that very uncommon, of course there are PEAR
classes you can use, for example XML_Tree or XML_Parser. Although slower
and more memory-intensive, I prefer using XML_Tree because it´s easier
to use.
I have written a small example script. Maybe this will help you getting
started:
<?php
/*
This one parses an XML config file like this:
<config>
<user>Testuser</user>
<password enctype='plain'>Testpwd</password>
</config>
...into an associative array like this:
array (
"user" => 'Testuser',
"password" => 'Testpwd',
"pwdEncType" => 'plain'
)
*/
function readConfigFileXML($configFile)
{
$conf = array();
// Check if file exists
if (is_file($configFile)) {
// Include PEAR::XML_Tree class definition
require_once('XML/Tree.php');
// Get tree object from config file
$tree = new XML_Tree($configFile);
// Get root node object from tree
$t = &$tree->getTreeFromFile();
// Iterate through all nodes below the root node
foreach ($t->children as $node) {
// Check the node name and set the corresponding array elements
switch($node->name) {
case "user":
$conf['user'] = $node->content;
break;
case "password":
$conf['password'] = $node->content;
// The node password can have attributes: Check them!
foreach($node->attributes as $attName=>$attValue) {
if ($attName == 'enctype') {
$conf['pwdEncType'] = $attValue;
}
}
break;
}
}
// Clean up
unset($t);
unset($tree);
// Return config array
return $conf;
} else {
// File not found
return false;
}
}
// Test the stuff
$myFile = "InsertNameOfTestFile";
$conf = array();
$conf = readConfigFileXML($myFile);
echo('<pre>');
print_r($conf);
echo('</pre>');
?>
Regards,
Markus
--
Markus Wolff <wolff@21st.de>