PHP - Dom Xpath问题

时间:2011-01-31 19:19:53

标签: php xml dom configuration xpath

使用此XML:

<?xml version="1.0" encoding="UTF-8" ?>
<databases>
    <default>
        <type>mysql</type>
        <host>localhost</host>
        <table-prefix></table-prefix>
        <username>root</username>
        <password></password>
        <charset>UTF-8</charset>
    </default>
    <test>
        <type>mysql</type>
        <host>localhost</host>
        <table-prefix></table-prefix>
        <username>root</username>
        <password></password>
        <charset>UTF-8</charset>
    </test>
</databases>

代码:

public function get($xpath = '/')
    {
        $dom_object = new DOMDocument();
        $dom_object->load($this->_filename);
        $domxpath_object = new DOMXpath($dom_object);

        $domnodelist_object = $domxpath_object->query($xpath);

        return $this->XMLConfigurationToArray($domnodelist_object);
    }

private function XMLConfigurationToArray(DOMNodeList $domnodelist_object)
    {
        $configuration_array = array();

        foreach ($domnodelist_object as $element)
        {
            if ($element->hasChildNodes())
            {
                foreach ($element->childNodes as $c)
                {
                    print_r('<pre>' . $element->tagName . '</pre>');
                }
            }
        }

        return $configuration_array;
    }

为什么要打印5次数据库?我叫get('/ databases')...... 谢谢。

2 个答案:

答案 0 :(得分:1)

还有空格,也是childNodes(textNodes)

忽略textNodes:

if($c->nodeType===1)
{
  echo('<pre>' . $c->tagName . '</pre>');
}

...或者还使用XPATH来检索子(元素) - 节点。

您也可以从一开始就忽略空格(如Gordon链接的主题中所述):

$dom_object = new DOMDocument();
$dom_object->preserveWhiteSpace=false;

答案 1 :(得分:1)

  

为什么要打印5次数据库?一世   call get('/ databases')

因为databases top元素有5个子节点:2个元素和3个(仅限空格)文本节点,围绕元素。