本文实现PHP解析config.xml配置文件,从中读取连接数据库所需的信息
config.xml
-------------------------------------------
<?xml version="1.0"?>
<configs>
<database>
<host>192.168.0.1</host>
<dbname>dbname</dbname>
<username>postgres</username>
<password>123456</password>
</database>
</configs>
解析文件parse.php
-------------------------------------------
<?php
class AminoAcid {
function AminoAcid ($aa) {
foreach ($aa as $k=>$v)
$this->$k = $aa[$k];
}
}
function readDatabase($filename) {
// read the xml database of aminoacids
$data = implode("",file($filename));
$parser = xml_parser_create();
xml_parser_set_option($parser,XML_OPTION_CASE_FOLDING,0);
xml_parser_set_option($parser,XML_OPTION_SKIP_WHITE,1);
xml_parse_into_struct($parser,$data,$values,$tags);
xml_parser_free($parser);
// loop through the structures
foreach ($tags as $key=>$val) {
if ($key == "database") {
$molranges = $val;
// each contiguous pair of array entries are the
// lower and upper range for each molecule definition
for ($i=0; $i < count($molranges); $i+=2) {
$offset = $molranges[$i] + 1;
$len = $molranges[$i + 1] - $offset;
$tdb[] = parseMol(array_slice($values, $offset, $len));
}
} else {
continue;
}
}
return $tdb;
}
function parseMol($mvalues) {
for ($i=0; $i < count($mvalues); $i++)
$mol[$mvalues[$i]["tag"]] = $mvalues[$i]["value"];
return new AminoAcid($mol);
//Return $mol;
}
$db = readDatabase("config.xml");
/*
echo("<pre>");
print_r($db);
echo("</pre>");
*/
foreach($db as $key=>$val)
{
echo($val->host);
}
?>
本文地址:http://com.8s8s.com/it/it28317.htm