Durante lo sviluppo della mia piattaforma CMS, mi sono imbattuta in un problema che non mi aspettavo e che documento qui per chi, come me, ha strippato un bel po' prima di uscirne.
Mettiamo di avere questo file XML da analizzare:
<?xml version='1.0' ?>
<books>
<book id='id_1'>
<title>My book</title>
</book>
</books>
Se nel mio codice php utilizzo la funzione getElementById('id_1') la funzione ritorna null.
La soluzione a questo problema è riportata in questa pagina.
In breve, è necessario definire l'attributo id come xml:id, definirne l'id con una stringa alfanumerica (ma non solo numerica) e ricordarsi di definire l'xml in questo modo:
// create a root
$eltRoot = $xmlDom->createElement("root");
$xmlDom->appendChild($eltRoot);
$eltChild = $xmlDom->createElement("child");
$eltRoot->appendChild($eltChild);
// add a id attribute
$attr = $xmlDom->createAttribute("xml:id"); // needs xml prefix or getElementById won't work
$eltChild->appendChild($attr);
/// create the text node and append to the created element
$tNode = $xmlDom->createTextNode("id_8120528");
$attr->appendChild($tNode);
$eltChild->setIdAttribute("xml:id", true); // VERY IMPORT or getElementById won't work
Mettiamo di avere questo file XML da analizzare:
<?xml version='1.0' ?>
<books>
<book id='id_1'>
<title>My book</title>
</book>
</books>
Se nel mio codice php utilizzo la funzione getElementById('id_1') la funzione ritorna null.
La soluzione a questo problema è riportata in questa pagina.
In breve, è necessario definire l'attributo id come xml:id, definirne l'id con una stringa alfanumerica (ma non solo numerica) e ricordarsi di definire l'xml in questo modo:
// create a root
$eltRoot = $xmlDom->createElement("root");
$xmlDom->appendChild($eltRoot);
$eltChild = $xmlDom->createElement("child");
$eltRoot->appendChild($eltChild);
// add a id attribute
$attr = $xmlDom->createAttribute("xml:id"); // needs xml prefix or getElementById won't work
$eltChild->appendChild($attr);
/// create the text node and append to the created element
$tNode = $xmlDom->createTextNode("id_8120528");
$attr->appendChild($tNode);
$eltChild->setIdAttribute("xml:id", true); // VERY IMPORT or getElementById won't work
Aggiungi un commento