简体   繁体   English

无法从PHP的递归函数获取xml元素属性值?

[英]Cannot get xml element attribute value from a recursive function in PHP?

I cannot get the attribute value of the xml element becaue everytime i click the link there is no value in id= but when view my xml there is a attribute value, why is this happening am i missing something? 我无法获取xml元素的属性值,因为每次单击链接时id=都没有值,但是当查看xml时存在属性值,为什么会发生这种情况?

Here is my PHP code: 这是我的PHP代码:

 <?php
function parse_recursive(SimpleXMLElement $element, $level = 0)
{
    $indent = str_repeat('', $level); 

    $value = trim((string) $element); 
    $children = $element->children(); 
    $attributes = $element->attributes();

    echo '<ul>';
    if(count($children) == 0 && !empty($value))
    {   
        if($element->getName() == 'GroupName'){
            echo '<li><a href="http://localhost:8080/test/test.php?id=';
            if(count($attributes) > 0)
            {
                foreach($attributes as $attribute)
                {
                    if($attribute->getName() == 'Id'){
                        echo $attribute;
                    }
                }
            }
            echo '">'.$element.'</a></li>';
        }
    }   

    if(count($children))
    {
        foreach($children as $child)
        {
            parse_recursive($child, $level+1);
        }
    }
    echo '</ul>';
}

$xml = new SimpleXMLElement('main.xml', null, true);
parse_recursive($xml);
?>

Here is my xml structure: 这是我的xml结构:

在此处输入图片说明

It appears that your code will only output anything for GroupName elements: 看来您的代码将只为GroupName元素输出任何内容:

if($element->getName() == 'GroupName'){

and it will only output the Id attributes of GroupName elements. 并且只会输出GroupName元素的Id属性。

The single GroupName in your source XML doesn't have an Id attribute. 源XML中的单个GroupName没有Id属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM