开发者

PHP - How do I read all attributes of XML items using simpleXML?

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.


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  


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜