<XML/>

XML Lab — Gestione File XML con PHP

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

studenti.xml
sorgente PHP commentato
// ① Percorso file (costante definita in cima)
define('XML_FILE', __DIR__ . '/studenti.xml');

// ② Crea il file solo se non esiste
if (!file_exists(XML_FILE)) {
  file_put_contents(XML_FILE, $defaultXML);
}

// ③ Crea un nuovo DOMDocument
$dom = new DOMDocument('1.0', 'UTF-8');
$dom->formatOutput = true;

// ④ Costruisce la struttura XML
$root = $dom->createElement('studenti');
$dom->appendChild($root);
$studente = $dom->createElement('studente');
$studente->setAttribute('id', 1);
$studente->appendChild(
  $dom->createElement('nome', 'Mario Rossi')
);
$root->appendChild($studente);

// ⑤ Salva su file fisico con save()
$dom->save(XML_FILE);  // ← crea/sovrascrive il file
// ① Carica il file XML da disco
$dom = new DOMDocument();
$dom->load(XML_FILE);  // ← legge dal file

// ② 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(XML_FILE);

// ① 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(XML_FILE);
$xpath = new DOMXPath($dom);

// ② Trova e modifica il valore
$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 su file
$dom->save(XML_FILE);  // ← sovrascrive il file
// ① Carica il documento
$dom = new DOMDocument();
$dom->formatOutput = true;
$dom->load(XML_FILE);
$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 su file
// NOTA: removeChild() richiede
// sempre il riferimento al padre!

$dom->save(XML_FILE);  // ← persistenza reale
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 su disco
live · file reale

▸ 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 su disco
  • loadXML() — carica da stringa
  • createElement() — crea nodo
  • setAttribute() — setta attributo
  • appendChild() — aggancia figlio
  • removeChild() — rimuove nodo
  • save() — scrive su file fisico

File XML — funzioni PHP

  • file_exists() — verifica se esiste
  • file_get_contents() — legge in stringa
  • file_put_contents() — scrive stringa
  • __DIR__ — percorso della cartella
  • $dom->load() — carica XML da file
  • $dom->save() — salva XML su file

Session vs File

Usa $_SESSION per:

  • Dati temporanei per-utente
  • Nessuna persistenza dopo logout

Usa file XML per:

  • Persistenza reale su disco
  • Dati condivisi tra utenti
  • Applicazioni reali/produzione