Ejemplo 3: Estructuras Anidadas
How to create hierarchies with several levels inside the same XML document
🎯 What does this example cover?
La anidación es lo que hace útil a XML para representar estructuras complejas: un elemento dentro de otro, dentro de otro. Elige cuántos niveles quieres generar (tienda → categoría → subcategoría → producto...) y PHP construirá el XML de forma recursiva, nivel a nivel, para que veas cómo cada nivel envuelve al siguiente.
Choose the depth
<tienda>
└── <categoria>
└── <subcategoria>
└── <producto>
└── <nombre>Example Producto</nombre>
Generated XML (3 levels)
<?xml version="1.0"?>
<tienda>
<categoria>
<subcategoria>
<producto>
<nombre>Example Producto</nombre>
</producto>
</subcategoria>
</categoria>
</tienda>
📖 Code Explanation
Recursive function in PHP
function construirNivel($padre, $etiquetas, $indice) {
if ($indice >= count($etiquetas)) {
return;
}
$hijo = $padre->addChild($etiquetas[$indice]);
if ($indice === count($etiquetas) - 1) {
$hijo->addChild('nombre', 'Ejemplo');
} else {
construirNivel($hijo, $etiquetas, $indice + 1);
}
}
📝 Recursion for nesting
What does it do? The function calls itself, passing the newly created element as the new "parent" and moving on to the next level in the tags array. Each call adds one more level of depth to the XML.
💡 Concept: nesting = real hierarchy
In the final DOM, each element generated in a recursive call ends up literally "inside" the previous element's opening and closing tags. That's why indenting the XML makes it look like a tree.
📝 Base case (stopping the recursion)
What does it do? Without this condition, the function would call itself forever. The "base case" indicates when to stop: when there are no more defined levels left.
🎯 Key Concepts Learned
Nesting in XML
- An element can contain other elements
- There's no level limit in the specification
- Each level must be closed correctly
Recursion
- Useful for structures of variable depth
- Needs a base case so it doesn't go on forever
- Each XML level corresponds to one call
Hierarchy Design
- More levels = more specific, but more complex
- You have to decide where the hierarchy ends
- It should reflect real relationships between the data
💪 Practical Exercise
Design your own hierarchy
- Try the 3 available levels and compare the depth of the resulting XML
- Think of a structure from your own domain (for example: school → grade → class → student) and write down how many levels you'd need
- What would happen if, instead of a single child per level, a
<categoria>could have several<producto>? Think about how the recursive function would change (hint: aforeachloop inside each level)
Multiple children per level
function construirNivelMultiple($padre, $datos) {
foreach ($datos as $item) {
$hijo = $padre->addChild('producto');
$hijo->addChild('nombre', $item['nombre']);
// Si \$item tuviera sub-hijos, se llamaría de nuevo aquí }
}
The key difference is using a foreach to create several sibling elements at the same level, instead of just one per level.