note 41308 added to ref.xml
| From: | askgopal at rn2 dot php dot net | Date: | Tue, 06 Apr 2004 07:47:25 +0000 |
| Subject: | note 41308 added to ref.xml | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-67695@lists.php.net to get a copy of this message | ||
A simple XML parser that would allow us to retrieve a value of an element using its path.
-- cut here --
<?
$_elements = array();
$_cur_path = '';
function parse_xml_config($file, $elems)
{
global $_elements;
$e = error_reporting(0);
if (($fp = fopen($file, 'r')) === false)
return ($elements);
$xph = xml_parser_create();
if (is_resource($xph)) {
xml_parser_set_option($xph, XML_OPTION_CASE_FOLDING, true);
if (!xml_set_element_handler($xph,
'start_elem_handler', 'end_elem_handler'))
return ($elements);
while (($data = fread($fp, 4096)))
xml_parse($xph, $data, feof($fp));
xml_parser_free($xph);
}
fclose($fp);
$elems = $_elements;
error_reporting($e);
}
function start_elem_handler($xph, $name, $attrs)
{
global $_elements, $_cur_path;
$e = error_reporting(0);
$_cur_path .= "/$name";
while (list($key,$val) = each($attrs)) {
$index = "$_cur_path/$key";
if (isset($_elements[$index])) {
$tmp = $_elements[$index];
$_elements[$index] = array();
array_push($_elements[$index], $tmp);
array_push($_elements[$index], $val);
} else
$_elements[$index] = $val;
}
error_reporting($e);
}
function end_elem_handler($xph, $name)
{
global $_elements, $_cur_path;
$_cur_path = dirname($_cur_path);
}
/* main prog */
$config = array();
parse_xml_config('/usr/local/etc/myconfig.xml', &$config);
print_r($config);
?>
-- paste --
if the input is:
<config>
<db host="localhost" username="foo" password="bar"
db="test"/>
<column name="x" value="x1"/>
<column name="y" value="y1"/>
</config>
the output would be:
Array
(
[/CONFIG/DB/HOST] => localhost
[/CONFIG/DB/USERNAME] => foo
[/CONFIG/DB/PASSWORD] => bar
[/CONFIG/DB/DB] => test
[/CONFIG/COLUMN/NAME] => Array
(
[0] => x
[1] => y
)
[/CONFIG/COLUMN/VALUE] => Array
(
[0] => x1
[1] => y1
)
)
----
Manual Page -- http://www.php.net/manual/en/ref.xml.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+41308
Delete -- http://master.php.net/manage/user-notes.php?action=delete+41308&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+41308&report=yes
Search -- http://master.php.net/manage/user-notes.php