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?

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.