<XML/>

XML Lab — Gestione File XML con PHP

TPSIT 5ª · Prof. Palmeri · IISS "Archimede" Cammarata

sorgente PHP commentato
// ① Crea un nuovo documento XML
$dom = new DOMDocument('1.0', 'UTF-8');
$dom->formatOutput = true;  // indentazione leggibile

// ② Crea l'elemento radice <studenti>
$root = $dom->createElement('studenti');
$dom->appendChild($root);

// ③ Crea un elemento figlio <studente>
$studente = $dom->createElement('studente');
$studente->setAttribute('id', 1);

// ④ Aggiunge i sotto-elementi
$studente->appendChild(
  $dom->createElement('nome', 'Mario Rossi')
);
$studente->appendChild(
  $dom->createElement('voto', 8)
);

// ⑤ Aggancia alla radice e salva
$root->appendChild($studente);
$dom->save('studenti.xml');
// ① Carica il file XML esistente
$dom = new DOMDocument();
$dom->load('studenti.xml');

// ② Ottieni tutti gli elementi <studente>
$studenti = $dom->getElementsByTagName('studente');

// ③ Itera con foreach
foreach ($studenti as $s) {

  // Legge attributo id
  $id = $s->getAttribute('id');

  // Legge valore dei nodi figli
  $nome = $s->getElementsByTagName('nome')
              ->item(0)->nodeValue;

  $voto = $s->getElementsByTagName('voto')
              ->item(0)->nodeValue;

  echo "ID: $id | $nome | Voto: $voto\n";
}
// XPath = linguaggio per navigare XML
$dom = new DOMDocument();
$dom->load('studenti.xml');

// ① Crea oggetto DOMXPath
$xpath = new DOMXPath($dom);

// ② Query: studenti con voto >= 8
$nodi = $xpath->query(
  '//studente[voto >= 8]'
);

// ③ Cerca per attributo specifico
$uno = $xpath->query(
  '//studente[@id="2"]'
)->item(0);

// ④ Cerca per testo contenuto
$r = $xpath->query(
  '//studente[contains(nome,"Rossi")]'
);

// Sintesi XPath utili:
// //tag          → tutti i nodi "tag"
// //tag[@attr]   → con attributo
// //tag[figlio]  → con elemento figlio
// //tag[pos()=1] → il primo nodo
// ① Carica e prepara
$dom = new DOMDocument();
$dom->formatOutput = true;
$dom->load('studenti.xml');
$xpath = new DOMXPath($dom);

// ② Modifica il valore di un nodo
$votoNodo = $xpath->query(
  '//studente[@id="1"]/voto'
)->item(0);

if ($votoNodo) {
  $votoNodo->nodeValue = 10;
}

// ③ Aggiunge un nuovo figlio
$st = $xpath->query(
  '//studente[@id="1"]'
)->item(0);

$st->appendChild(
  $dom->createElement('classe', '5A')
);

// ④ Salva le modifiche
$dom->save('studenti.xml');
// ① Carica il documento
$dom = new DOMDocument();
$dom->formatOutput = true;
$dom->load('studenti.xml');
$xpath = new DOMXPath($dom);

// ② Trova il nodo da eliminare
$nodo = $xpath->query(
  '//studente[@id="3"]'
)->item(0);

// ③ Rimuovi tramite il nodo padre
if ($nodo) {
  $nodo->parentNode->removeChild($nodo);
}

// ④ Salva
// NOTA: removeChild() richiede
// sempre il riferimento al padre
// Non esiste deleteNode() in PHP!

$dom->save('studenti.xml');
laboratorio interattivo — prova le operazioni
📋 Leggi tutti gli studenti
getElementsByTagName()
🔍 Filtro XPath per voto minimo
//studente[voto >= N]
🔎 Cerca per nome (contains)
➕ Aggiungi studente
✏️ Modifica voto (per ID)
🗑️ Elimina studente (per ID)
output PHP
// Clicca un'operazione per vedere il risultato PHP qui ↑ // Il file XML a destra si aggiorna in tempo reale
studenti.xml — stato corrente
live

▸ TEORIA RAPIDA

Struttura XML

  • Prologo: <?xml version="1.0"?>
  • Radice: unico elemento genitore
  • Elementi: tag apertura + chiusura
  • Attributi: coppie nome="valore"
  • Testo: contenuto tra i tag

DOMDocument — metodi chiave

  • load() — carica da file
  • loadXML() — carica da stringa
  • createElement() — crea nodo
  • setAttribute() — setta attributo
  • appendChild() — aggancia figlio
  • removeChild() — rimuove nodo
  • save() — scrive su file

XPath — sintassi essenziale

  • //tag — tutti i nodi "tag"
  • //tag[@id="1"] — per attributo
  • //tag[figlio >= 8] — condizione
  • //tag[contains(t,"x")] — testo
  • item(0) — primo risultato
  • nodeValue — legge/scrive testo

SimpleXML vs DOMDocument

Usa SimpleXML per:

  • Lettura rapida e semplice
  • Pochi nodi, struttura piatta

Usa DOMDocument per:

  • Scrittura, modifica, eliminazione
  • Query XPath complesse
  • Applicazioni reali/produzione