note 70433 modified in ref.simplexml by danbrown
| From: | danbrown@php.net | Date: | Mon, 18 May 2009 01:24:40 +0000 |
| Subject: | note 70433 modified in ref.simplexml by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-155528@lists.php.net to get a copy of this message | ||
simplexml provides a neat way to do 'ini' files. Preferences for any number of users can
be held in a single XML file having elements for each user name with user specific preferences as
attributes of child elements. The separate <pref/>'s could of course be combined as
multiple attributes of a single <pref/> element but this could get unwieldy.
In the sample code below the makeXML() function uses the simplexml_load_string function to generate
some XML to play with and the readPrefs() function parses the requested users preferences into an
array.
<?php
function makeXML() {
$xmlString = <<<XML
<preferences>
<johndoe>
<pref color="#FFFFFF"/>
<pref size="14"/>
<pref font="Verdana"/>
</johndoe>
<janedoe>
<pref color="#000000"/>
<pref size="16"/>
<pref font="Georgia"/>
</janedoe>
</preferences>
XML;
return simplexml_load_string($xmlString);
}
function readPrefs($user, $xml) {
foreach($xml->$user as $arr);
$n = count($arr);
for($i=0;$i<$n;$i++) {
foreach($xml->$user->pref[$i]->attributes() as $a=>$b) {
$prefs[$a] = (string)$b;
}
}
print_r($prefs);
}
readPrefs('johndoe', makeXML());
?>
--was--
simplexml provides a neat way to do 'ini' files. Preferences for any number of users can
be held in a single XML file having elements for each user name with user specific preferences as
attributes of child elements. The separate <pref/>'s could of course be combined as
multiple attributes of a single <pref/> element but this could get unwieldy.
In the sample code below the makeXML() function uses the simplexml_load_string function to generate
some XML to play with and the readPrefs() function parses the requested users preferences into an
array.
<?php
function makeXML() {
$xmlString = <<<XML
<preferences>
<johndoe>
<pref color="#FFFFFF"/>
<pref size="14"/>
<pref font="Verdana"/>
</johndoe>
<janedoe>
<pref color="#000000"/>
<pref size="16"/>
<pref font="Georgia"/>
</janedoe>
</preferences>
XML;
return simplexml_load_string($xmlString);
}
function readPrefs($user, $xml) {
foreach($xml->$user as $arr);
$n = count($arr);
for($i=0;$i<$n;$i++) {
foreach($xml->$user->pref[$i]->attributes() as $a=>$b) {
$prefs[$a] = (string)$b;
}
}
print_r($prefs);
}
readPrefs('johndoe', makeXML());
?>
http://php.net/manual/en/ref.simplexml.php