Flocons de Pâques

Astuces de programmation

PHP : transformToDoc vs. transformToXML ?

 2006-09-02

English translation follows.

Dans la plupart des cas, si vous attendez une sortie XML (ou XHTML)  vous avez intérêt à utiliser transformToXML() plutôt que transformToDoc(). Vous obtenez un meilleur contrôle sur les attributs de xsl:output, notamment (mais pas uniquement) omit-xml-declaration.

A la place de  :
$proc = new XSLTProcessor();
$proc->importStylesheet($xsl);
$dom = $proc->transformToDoc($xml);
echo $dom->saveXML();

utilisez :
$proc = new XSLTProcessor();
$proc->importStylesheet($xsl);
$newXml = $proc->transformToXML($xml);
echo $newXml;
Dans le premier cas, <?xml version="1.0" encoding="utf-8"?> est ajouté quoique vous fassiez avec omit-xml-declaration, tandis que transformToXML() tient compte de la valeur de cet attribut.

English translation :
In most cases if you expect XML (or XHTML) as output you better use transformToXML() directly rather than transformToDoc(). You gain better control over xsl:output attributes, notably omit-xml-declaration (but not only).

Instead of :
$proc = new XSLTProcessor();
$proc->importStylesheet($xsl);
$dom = $proc->transformToDoc($xml);
echo $dom->saveXML();

do use :
$proc = new XSLTProcessor();
$proc->importStylesheet($xsl);
$newXml = $proc->transformToXML($xml);
echo $newXml;

In the first case, <?xml version="1.0" encoding="utf-8"?> is added whatever you set the omit-xml-declaration while transformToXML() take the attribute into account.