MasetrPage.xml
:
<?xml version="1.0" encoding="UTF-8"?>
<PAGE
xmlns:PHOENIX = 'PHOENIX'
xmlns:PHOENIX.CORE = 'PHOENIX/CORE'
xmlns:PHOENIX.CORE.PAGE = 'PHOENIX/CORE/PAGE'
xmlns:PHOENIX.CORE.COMPILER = 'PHOENIX/CORE/COMPILER'
>
</PAGE>
Page.xml
:
<PHEONIX.CORE:EXAMPLE.ELEMENT />
<PHEONIX.CORE:EXAMPLE.ELEMENT2 />
Now I want to include the Page.xml
content inside the MasterPage.xml
PAGE
tag.
My PHP Code:
//[i] Initialize new \DOMDocument from from PageMaster.xml.
$pageDocument = \DOMDocument::load('PageMaster.xml');
//[i] Create fragment from pageDocument and append content from page XML.
$pageDocument_frag = $pageDocument->createDocumentFragment();
$pageDocument_frag->appendXML(file_get_contents('Page.xml'));
But here I get an error that the namespaces are not defined inside the Page.xml
. But for my project I don't want to define the namespaces inside the Page.xml
If you don't define the namespaces inside the fragment string then it will not be valid XML. Namespace prefixes are both exchangeable and optional. The prefixes do not define the namespace, the xmlns*-attributes do.
The following 3 examples all parse to the same namespace and local node name:
<f:foo xmlns:f="urn:foo-ns"/>
<foo:foo xmlns:foo="urn:foo-ns"/>
<foo xmlns="urn:foo-ns"/>
All result in an element node with the local name foo
and the namespace urn:foo-ns
. You can read the node name as {urn:foo-ns}foo
.
However to make the XML input for users easier you can define a set prefixes for you namespaces. You take the input an wrap it into an tag that defines the namespace. After that you can parse it as a fragment and copy the childnodes.
$xhtml = <<<'XHTML'
<div>
<p>Some Content.</p>
</div>
XHTML;
$document = new DOMDocument();
$import = $document->createDocumentFragment();
$import->appendXml(
'<section xmlns="http://www.w3.org/1999/xhtml">'.$xhtml.'</section>'
);
$fragment = $document->createDocumentFragment();
foreach ($import->childNodes->item(0)->childNodes as $node) {
$fragment->appendChild($node->cloneNode(TRUE));
}
$document->formatOutput = TRUE;
echo $document->saveXml($fragment);
Output:
<div xmlns="http://www.w3.org/1999/xhtml">
<p>Some Content.</p>
</div>