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)