note 41308 deleted from ref.xml by bjori
| From: | bjori@php.net | Date: | Mon, 09 Oct 2006 11:17:52 +0000 |
| Subject: | note 41308 deleted from ref.xml by bjori | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-118307@lists.php.net to get a copy of this message | ||
Note Submitter: askgopal [AT] sify [PERIOD] com
----
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
)
)