DOM in PHP - Document Object Model

Manipulate XML and HTML documents like a professional

XML/HTML
structure Hierarchical
Reading/Writing

🌳 What is the DOM in PHP?

DOM (Document Object Model) is a PHP extension that lets you manipulate XML and HTML documents as a tree structure. You can navigate, modify, add or remove elements programmatically.

Document XML
<inventario>
<pieza id="10">
<nombre> Minimalist vase </nombre>
<precio> 55.055 </precio>

📂 Reading XML with DOM

Practical example using the file ceramica.xml:

ceramica.xml

<?xml version="1.0" encoding="UTF-8"?>
<inventario>
    <pieza id="10">
        <nombre>Jarron minimalista</nombre>
        <precio>55.055</precio>
    </pieza>
</inventario>

PHP Code (reading)

<?php
$dom = new DOMDocument();
$dom->load("ceramica.xml");

$piezas = $dom->getElementsByTagName("pieza");

foreach ($piezas as $pieza) {
    $nombre = $pieza->getElementsByTagName("nombre")->item(0)->nodeValue;
    $precio = $pieza->getElementsByTagName("precio")->item(0)->nodeValue;
    
    echo "Producto: $nombre \nPrecio: $precio €\n";
}
?>

📊 Execution result:

🔧 Main Methods of the DOM

Creation

  • new DOMDocument()
  • createElement()
  • createAttribute()
  • createTextNode()

Search

  • getElementsByTagName()
  • getElementById()
  • getAttribute()
  • item()

Modification

  • nodeValue = "nuevo"
  • setAttribute()
  • appendChild()
  • removeChild()

Saving

  • save()
  • saveXML()
  • saveHTML()

💰 Interactive Example: Update Prices

The following example increases the product's price by 10%:

Before the update:

<?xml version="1.0"?>

After (+10%):

<?xml version="1.0"?>

Code used:

<?php
$dom = new DOMDocument();
$dom->load("ceramica.xml");
$piezas = $dom->getElementsByTagName("pieza");

foreach ($piezas as $pieza) {
    // Obtener el precio actual
    $precioNode = $pieza->getElementsByTagName("precio")->item(0);
    $precioActual = $precioNode->nodeValue;
    
    // Calcular nuevo precio (+10%)
    $nuevoPrecio = $precioActual * 1.10;
    
    // Actualizar el valor
    $precioNode->nodeValue = $nuevoPrecio;
}

// Guardar los cambios
$dom->save("ceramica.xml");
echo t('Archivo actualizado guardado correctamente.');
?>

🏗️ DOM Structure

Node Types:

  • Document - XML_DOCUMENT_NODE
  • Element - XML_ELEMENT_NODE
  • Attribute - XML_ATTRIBUTE_NODE
  • Text - XML_TEXT_NODE
  • Comment - XML_COMMENT_NODE

Important properties:

  • nodeName - Node name
  • nodeValue - Node value
  • nodeType - Node type (constant)
  • parentNode - Parent node
  • childNodes - Child nodes
  • attributes - Node attributes

➕ Crear Nuevo XML desde Cero

<?xml version="1.0" encoding="UTF-8"?>
<biblioteca>
    <libro id="1">
        <titulo>El Quijote</titulo>
        <autor>Miguel de Cervantes</autor>
        <precio>29.99</precio>
    </libro>
</biblioteca>

Código para crear el XML:

<?php
$dom = new DOMDocument('1.0', 'UTF-8');
$dom->formatOutput = true;

// Crear elemento raíz
$biblioteca = $dom->createElement('biblioteca');
$dom->appendChild($biblioteca);

// Crear elemento libro
$libro = $dom->createElement('libro');
$biblioteca->appendChild($libro);

// Agregar atributo id
$id = $dom->createAttribute('id');
$id->value = '1';
$libro->appendChild($id);

// Agregar elementos hijos
$titulo = $dom->createElement('titulo', 'El Quijote');
$libro->appendChild($titulo);

$autor = $dom->createElement('autor', 'Miguel de Cervantes');
$libro->appendChild($autor);

$precio = $dom->createElement('precio', '29.99');
$libro->appendChild($precio);

echo $dom->saveXML();
?>

⚖️ DOM vs Other Methods

Method Advantages Disadvantages Recommended use
DOM ✅ Complete, reading/writing, easy navigation ❌ Uses a lot of memory with large files Files XML/HTML small/medium
SimpleXML ✅ Simple, easy to use ❌ Limited for complex modifications Quick reading of XML
XMLReader/XMLWriter ✅ Low memory usage ❌ More complex to code Files XML very large

✏️ DOM Practice Area

XML example:

PHP DOM Code:

Result:

Ejecuta el código para ver el resultado...

💡 Tips for working with DOM

Output format

Use $dom->formatOutput = true to get XML readable

Preserve whitespace

$dom->preserveWhiteSpace = false to clean up the XML

Validation

Use $dom->validate() to validate against DTD

XPath

DOM Combine XPath with XPath for more powerful searches

Error handling

Use libxml_use_internal_errors(true) for custom error handling

Memory

For very large files (>10MB), consider XMLReader