MekeniKine
MekeniKine

Reputation: 285

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?

Here is my PHP code:

 <?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:

enter image description here

Upvotes: 0

Views: 504

Answers (1)

JLRishe
JLRishe

Reputation: 101672

It appears that your code will only output anything for GroupName elements:

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

and it will only output the Id attributes of GroupName elements.

The single GroupName in your source XML doesn't have an Id attribute.

Upvotes: 1

Related Questions