Example 2: XML Attributes
How to add metadata to an element without creating more child elements
🎯 What does this example cover?
The same piece of data can be modeled as a child element or as an attribute. This example lets you build a <producto> and see the difference live: id, categoria and moneda are stored as attributes (inside the opening tag itself), while precio is stored as a child element, so you can compare both approaches in the same document.
Configure the product
Generated XML
<producto ...>. Precio, en cambio, es un elemento completo aparte. <?xml version="1.0"?> <producto id="045" categoria="ropa-deportiva" moneda="EUR">Camiseta técnica<precio>19.95</precio></producto>
📖 Code Explanation
Complete PHP Code
<?php
$xml = new SimpleXMLElement('<producto/>');
$xml->addAttribute('id', $id);
$xml->addAttribute('categoria', $categoria);
$xml->addAttribute('moneda', $moneda);
$xml[0] = $nombre; // the node's text <producto>
$xml->addChild('precio', $precio); // child element
echo $xml->asXML();
?>
📝 addAttribute()
What does it do? Adds a name="value" pair inside the element's opening tag, without creating a new nested element.
💡 Concept: attribute vs. element
An attribute describes or identifies the element (metadata), while a child element usually represents its own data, substantial enough to have its own content and, potentially, its own sub-elements.
📝 The node's own text
What does it do? Assigns the text content of the <producto> element (what goes between the opening and closing tags), instead of creating a new child.
📝 When to use each
Use attributes for identifiers, flags or short metadata (id, lang, moneda).
Use child elements when the data can have its own structure, be meaningfully empty, or need multiple values (several <etiqueta>, for example).
🎯 Key Concepts Learned
Attribute Syntax
- They go inside the opening tag
- Always in quotes:
id="045" - An element can have several attributes
Attribute vs. Element
- Attribute: simple, single metadata
- Element: data with possible structure
- There's no absolute rule, it's a design choice
SimpleXML
addAttribute()adds attributes$nodo[0] = valorsets the node's textaddChild()still works for children
💪 Practical Exercise
Redesign the data model
- Change
categoriafrom an attribute to a child element. Which line of code would you change? - Add a new attribute
stockwith the available quantity - Think of a case where the same data (for example, "date") would make sense as an attribute, and another where it would make more sense as an element
Categoría as a child element
// Antes: \$xml->addAttribute('categoria', \$categoria);
// Después:$xml->addChild('categoria', $categoria);
The result would be <categoria>ropa-deportiva</categoria> as a child of <producto>, instead of an attribute inside the tag.
New stock attribute
$xml->addAttribute('stock', '12');