(PHP 5, PHP 7, PHP 8)
DOMDocument::xinclude — Reemplaza los XIncludes en un objeto DOMDocument
Este método reemplaza los » XIncludes en un objeto DOMDocument.
Nota:
Dado que la biblioteca libxml2 resuelve automáticamente las entidades, este método puede producir resultados no esperados si el fichero XML incluido tiene una DTD adjunta.
Devuelve el número de XIncludes del documento, -1 si ocurre un error
durante el proceso, o false si no hay sustitución.
Ejemplo #1 Ejemplo con DOMDocument::xinclude()
<?php
$xml = <<<EOD
<?xml version="1.0" ?>
<chapter xmlns:xi="http://www.w3.org/2001/XInclude">
<title>Los libros de otra persona</title>
<para>
<xi:include href="examples/book.xml">
<xi:fallback>
<error>xinclude: book.xml no ha sido encontrado</error>
</xi:fallback>
</xi:include>
</para>
</chapter>
EOD;
$dom = new DOMDocument;
// Se desea un bonito formato de salida
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
// carga del string XML definido anteriormente
$dom->loadXML($xml);
// reemplazo de los xincludes
$dom->xinclude();
echo $dom->saveXML();
?>Resultado del ejemplo anterior es similar a:
<?xml version="1.0"?> <chapter xmlns:xi="http://www.w3.org/2001/XInclude"> <title>Los libros de otra persona</title> <para> <row xml:base="/home/didou/book.xml"> <entry>The Grapes of Wrath</entry> <entry>John Steinbeck</entry> <entry>en</entry> <entry>0140186409</entry> </row> <row xml:base="/home/didou/book.xml"> <entry>The Pearl</entry> <entry>John Steinbeck</entry> <entry>en</entry> <entry>014017737X</entry> </row> <row xml:base="/home/didou/book.xml"> <entry>Samarcande</entry> <entry>Amine Maalouf</entry> <entry>fr</entry> <entry>2253051209</entry> </row> </para> </chapter>
If you use the loadXML() method instead of the load() one (let's say, to process the XML string before loading and parsing it), you will have problems with xinclude(), because the parser will not know where to find the files to include.
Using chdir() before xinclude() will not help.
The solution is to set the documentURI property of the DOMDocument object accordingly to it's original filename, and everything will work fine !
<?php
$xml = file_get_contents($file);
$xml = do_something_with($xml);
$doc = new DOMDocument;
$doc->documentURI = $file;
$doc->loadXML($xml);
$doc->xinclude();
?>