1

I'm making a script, that reads through the passed XML file and displays the source code. I've got it almost done, but the item attributes .. I can't find a way to catch them. Here's the code:

$xml = simplexml_load_file("path/to/file.xml");

    showTree($xml->children(), 0);

    function showTree($value, $i) {

        if($value == '') {

            foreach($value as $name2 => $value2) {

                echo str_repeat('--', $i)." <$name2> \n";
                    showTree($value2, ($i+1));
                echo str_repeat('--', $i)." </$name2> \n";
            }

        } else { echo str_repeat('--', $i)." ".trim($value)."\n"; }

    } // end: function  

As I said, it works fine, but doesn't display the attributes, for example:

<item id=2>Item</item>

returns only the:

<item>Item</item>

Thanks for any responses, Mike.

2 Answers 2

1

Unless I missread your code something like this should probably be about right.

$xml = simplexml_load_file("path/to/file.xml");

    showTree($xml->children(), 0);

    function showTree($value, $i) {

        if($value == '') {

            foreach($value as $name2 => $value2) {

              $attribsStr = '';
              foreach($value2->attributes() as $attribName => $attribValue) {
                $attribsStr .= $attribName . '="' . $attribValue . '"' . ' ';
              }

              echo str_repeat('--', $i)." <$name2 $attribsStr> \n";
                showTree($value2, ($i+1));
              echo str_repeat('--', $i)." </$name2> \n";
            }

        } else { echo str_repeat('--', $i)." ".trim($value)."\n"; }

    } // end: function  
Sign up to request clarification or add additional context in comments.

Comments

1

Have a look at http://php.net/manual/en/simplexmlelement.attributes.php

1 Comment

I did, tryed some code and when it didn't work, I decided to ask on SO :]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.