我创建了一个读取值和值的节点名称的类,并将其组合到数组中,以便将其用作XML中的配置的简单快速访问。但是这个解决方案只有在生成底层节点时才有效,XML就像这样。
<?xml version="1.0" encoding="ISO-8859-2"?>
<settings>
<const>
<inscript>true</inscript>
<title>Template</title>
</const>
<meta>
</meta>
<db>
<user>user</user>
<pass>pass</pass>
<host>host</host>
<name>name</name>
</db>
<path>
<style>
<css>/Template/view/www/style/</css>
<img>/Template/view/www/style/img</img>
</style>
</path>
</settings>
现在我想得到整个db节点并将其作为一个数组返回,其中node name wold是键和节点值value。但我坚持这一点。这是我到目前为止所做的。
class config {
private static $xml = "lib/config/settings.xml";
private static $xmlRoot = "settings";
public static function loadConfig($value) {
$domDocument = new DOMDocument();
$domDocument->load(self::$xml);
$settings = $domDocument->getElementsByTagName(self::$xmlRoot);
try {
foreach ($settings as $setting) {
$configValue = $setting->getElementsByTagName($value)->item(0)->nodeValue;
$configNode = $setting->getElementsByTagName($value)->item(0)->nodeName;
$test = $setting->getElementsByTagName("path")->item(0)->childNodes->item(2)->nodeName;
var_dump($test);
}
$configValue = explode(' ', trim(preg_replace( '/\s+/', ' ', $configValue)));
$configNode = explode(' ', trim(preg_replace( '/\s+/', ' ', $configNode)));
$configArray = array_combine($configNode, $configValue);
return $configArray;
}
catch(Exception $e) {
echo '<h1>Błąd - '.$e->getMessage().'</h1>';
}
}
}
答案 0 :(得分:0)
您可以像这样使用XPath:
$xp = new DOMXPath($domDocument);
$config = array();
foreach ($xp->query('./db/*') as $node) {
$config[$node->nodeName] = $node->textContent;
}
return $config;