0

My PHP:

$url = '../build.xml';
$xml = simplexml_load_file($url);

foreach($xml->css as $css) {
    echo (string) $css->element['id']."{";
    foreach($xml->css->element->csstag as $tag) {
        $temp = $tag->title.": ".$tag->value.";";
        echo $temp;
    }
    echo "}";
}

My XML:

<root>
    <css>
    <element id="body">
        <csstag><title>background-color</title><value>#FFF</value></csstag>
        <csstag><title>color</title><value>#333</value></csstag>
        <csstag><title>font-family</title><value>Verdana, Geneva, sans-serif</value></csstag>
    </element>
    <element id="#header">
        <csstag><title>background-color</title><value>#444</value></csstag>
        <csstag><title>color</title><value>#FFF</value></csstag>
        <csstag><title>border-bottom</title><value>#333 5px solid</value></csstag>
    </element>
    <element id="#footer">
        <csstag><title>background-color</title><value>#444</value></csstag>
        <csstag><title>color</title><value>#FFF</value></csstag>
        <csstag><title>border-top</title><value>#333 5px solid</value></csstag>
    </element>
    </css>
</root>

I can't find what's wrong!

The first issue is that the first foreach is showing just the first <element> node, I know that's because I've told it to foreach each <css> tag, but I couldn't think of any other way do echo the attribute of the <element> nodes.

The second thing is that the second foreach is echoing nothing back!

Can anyone see the problem in the code? Thank you in advance!

1 Answer 1

1

You're missing a foreach loop, you need another level

foreach($xml->css as $css) {
    foreach($xml->css->element as $elem){ // foreach element
        echo (string) $elem['id']."{";    // id for each element
        foreach($elem->csstag as $tag) {
            $temp = $tag->title.": ".$tag->value.";";
            echo $temp;
    }
    echo "}\n"; //\n to make the css look neater
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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