Go through an XML document with SimpleXML

0

Good! I'm trying to traverse the data of an xml document, for the time being, but when I have to deal with the attributes of some tags, it's when I get lost.

$agenda = new SimpleXMLElement("prueba.xml", 0, true);
foreach($agenda->personas->persona as $persona) {
    echo $persona->nombre . "<br>";
    echo $persona->apellidos . "<br>";
    echo $persona->fechanac . "<br>";
    echo $persona->ciudad . "<br>";
    foreach($persona->contacto["tipo"] as $contacto) {
        switch($contacto){
            case "email":
                echo "<b>Email: " . $contacto . "<br>";
                break;
            case "tlf":
                echo "<b>Teléfono: " . $contacto . "<br>";
                break;
        }
    }
    echo "<br>";

}

This shows all the data correctly but passes olympically on the labels that have the type attribute

    
asked by Rodrypaladin 20.09.2016 в 21:49
source

1 answer

1

I autorespondo to have solved it, I share it in case someone else has the same question.

The error was in the foreach that traverses the attributes.

foreach($persona->contacto as $contacto) {
        switch($contacto["tipo"]){
            case "email":
                echo "<b>Email: </b>" . $contacto . "<br>";
                break;
            case "tlf":
                echo "<b>Teléfono: </b>" . $contacto . "<br>";
                break;
        }
    }

With that form we show a code or another depending on the type of value of that attribute.

The final code remains like this

$agenda = new SimpleXMLElement("prueba.xml", 0, true);

foreach($agenda->personas->persona as $persona) {
    echo $persona->nombre . "<br>";
    echo $persona->apellidos . "<br>";
    echo $persona->fechanac . "<br>";
    echo $persona->ciudad . "<br>";

    foreach($persona->contacto as $contacto) {
        switch($contacto["tipo"]){
            case "email":
                echo "<b>Email: </b>" . $contacto . "<br>";
                break;
            case "tlf":
                echo "<b>Teléfono: </b>" . $contacto . "<br>";
                break;
        }
    }
    echo "<br>";

}
    
answered by 20.09.2016 в 22:12