Ejemplo 1: XML Básico
The fundamental structure of an XML document with simple data
🎯 What does this example cover?
This interactive example generates a valid XML document in real time from the data you enter in the form. Every time you add a book, PHP builds a new
Add a book to the library
XML generated in real time
<?xml version="1.0"?>
<biblioteca>
<libro>
<titulo>El Quijote</titulo>
<autor>Miguel de Cervantes</autor>
<anio>1605</anio>
</libro>
</biblioteca>
📖 Code Explanation
Complete PHP Code
<?php
$xml = new SimpleXMLElement('<biblioteca/>');
foreach ($libros as $libro) {
$nodoLibro = $xml->addChild('libro');
$nodoLibro->addChild('titulo', $libro['titulo']);
$nodoLibro->addChild('autor', $libro['autor']);
$nodoLibro->addChild('anio', $libro['anio']);
}
echo $xml->asXML();
?>
📝 Create the root element
What does it do? Crea un documento XML nuevo cuyo único elemento raíz es <biblioteca>. Todo XML necesita exactamente un elemento raíz que envuelva al resto.
💡 Concept: SimpleXML
SimpleXML is the simplest way to work with XML in PHP: it turns the document into a navigable object, very convenient for basic reading and creation.
📝 Add child elements
$nodoLibro->addChild('titulo', $libro['titulo']);
What does it do? addChild() creates a new element inside the node it's called on. First we create <libro> inside <biblioteca>, and then <titulo>, <autor> and <anio> inside <libro>.
Why this way? This is the essence of XML: data is organized in a hierarchy of elements, not a flat list.
📝 Export the XML
What does it do? Converts the SimpleXML object back into XML text, including the <?xml version="1.0"?> declaration. This is what this example formats and shows you on screen.
🎯 Key Concepts Learned
Root Element
- An XML document can only have one root element
- All other elements go inside it
- Here it's
<biblioteca>
Element Hierarchy
- Each
<libro>is a child of<biblioteca> <titulo>,<autor>and<anio>are children of<libro>- Nesting represents relationships between data
SimpleXML in PHP
new SimpleXMLElement()creates the documentaddChild()adds nodesasXML()exports the result as text
💪 Practical Exercise
Expand the XML library
Try these changes to reinforce what you've learned:
- Add 3 different books using the form and watch how the XML grows
- Think about what new field you'd add (for example
<genero>) and where it would go in the hierarchy - Write by hand, on paper, the equivalent XML for your favorite book
- Compare: what would happen if
<titulo>were outside<libro>?
Add a "género" field
$nodoLibro->addChild('titulo', $libro['titulo']);
$nodoLibro->addChild('autor', $libro['autor']);
$nodoLibro->addChild('anio', $libro['anio']);
$nodoLibro->addChild('genero', $libro['genero']); // nuevo campo, mismo nivel que los anteriores
The new field goes at the same level as titulo, autor and anio, because it describes one more property of the same book, not of the whole library.