Jump to content

Newbie XML question: elements with children print strangely


Phasma Felis

Recommended Posts

I have a file test.xml, like this:

<?xml version="1.0"?>
<elements>
        <element name="element1">This is an element.</element>
        <element name="element2">
                <child name="child1">A child element.</child>
                <child name="child2">Another child element.</child>
        </element>
        <element name="element3">This is also an element.</element>
</elements>

And I want to iterate over all elements, like this:

<?php
function iterateXml($elements, $depth) {
    foreach ($elements as $element) {
        for ($i=0; $i<$depth; $i++) echo "\t";     //indent children
        echo $element->getName(), " => $element\n";
        iterateXml($element->children(), $depth+1);
    }
}

$xml = simplexml_load_file("test.xml");
iterateXml($xml, 0);
?>

When I run that program, I get this:

element => This is an element.
element => 



        child => A child element.
        child => Another child element.
element => This is also an element.

Where's the whitespace after the second element coming from? How do I get just the textual content without the whitespace?

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.