0

With this 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>

Code:

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;
    }

Why it prints out databases 5 times? I call get('/databases') ... Thank you.

thomas
  • 1

2 Answers2

1

There are also whitespaces, which are childNodes too (textNodes)

Ignore the textNodes:

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

...or use also XPATH to retrieve the child(element)-nodes.

You can also ignore the whitespaces from the start(as described in the topic linked by Gordon):

$dom_object = new DOMDocument();
$dom_object->preserveWhiteSpace=false;
Dr.Molle
  • 116,463
  • 16
  • 195
  • 201
  • do you mean tabs == whitespaces? so, in xml, i cannot have whitespaces? will every whitespace be an textnode? thank you. – thomas Jan 31 '11 at 19:46
  • yes, tabs, linebreaks, spaces. You have one after ``, one after `` and one after `` – Dr.Molle Jan 31 '11 at 19:49
  • 1
    @thomas: No, every text node is going to be a text node. Preserving or stripping white space only text nodes is usually a matter or XML parser configuration. Check for [@Gordon's answer](http://stackoverflow.com/questions/4598409/printing-content-of-a-xml-file-using-xml-dom/4599724#4599724) –  Jan 31 '11 at 19:55
1

Why it prints out databases 5 times? I call get('/databases')

Because the databases top element has 5 children nodes: 2 elements and three (whitespace-only)text nodes, surrounding the elements.

Dimitre Novatchev
  • 240,661
  • 26
  • 293
  • 431