DOMDocument->createDocumentFragment()

(no version information, might be only in CVS)

DOMDocument->createDocumentFragment() -- Create new document fragment

说明

class DOMDocument {

DOMDocumentFragment createDocumentFragment ( void )

}

This function creates a new instance of class DOMDocumentFragment. 本节点不会出现在文档中,除非是用例如 DOMNode->appendChild() 函数来将其插入。

返回值

The new DOMDocumentFragment or FALSE if an error occured.


add a note add a note User Contributed Notes
xavier.pinard at laposte.net
13-Jul-2006 10:08
The interest of fragment is I think :

 - only nodes inside the fragment are inserted,
   not the fragment itself when you insert the fragment
 - you can append String litteral with the method
   DOMDocumentFragment->appendXML()

So, a fragment may look like this :

part of document<li>bla bla </li> ...

This fragment is describe with a fragment description
 that may look like this is you use
it as an "XML Fragment Interchange" :

<f:fcs xmlns:f="http://www.w3.org/2001/02/xml-fragment"

[...]

<myOriginalStructure>

[...]

<f:fragbody/>

[...]

</myOriginalStructure>

cf :: http://www.w3.org/TR/xml-fragment

An example could be for "XML Fragment Interchange":

$dom = new DomDocument();
$frag = $dom->createDocumentFragment();
$fragbody = $dom->createElementNS(
 'http://www.w3.org/2001/02/xml-package',
 'p:body'
);
$frag->appendXML(
 'test fragment<ilo>data</ilo> +
 an object property +
 something else '
);
$fragbody->appendChild($frag);
$dom->appendChild($fragbody);
var_dump($dom->saveXML());
jb at jbpros dot com
13-May-2006 11:04
DOMDocumentFragment can be very useful with XPath: you may need to apply an XPath expression to a list of nodes.

$dom_doc = new DOMDocument();
$dom_fragment = $dom_doc->createDocumentFragment();
$dom_element_a1 = $dom_fragment->appendChild($dom_doc->createElement('a', 'first node'));
$dom_element_a2 = $dom_fragment->appendChild($dom_doc->createElement('a', 'second node'));
$xpath = new DOMXpath($dom_doc);
$nodes = $xpath->query('a', $dom_fragment);

foreach ($nodes as $node) {
   echo $node->textContent . "\n";
}

This way you do not need to embed the nodes within a parent element that could be returned by the xpath expression when you do not want this to happen.
03-Dec-2005 04:58
You can append document fragments to documents. This will append their nodes instead of fragment node itself.
So if you're asking yourself "how do I make function that returns more than one node" - that is the answer.
Naonak
16-Sep-2005 01:31
Example :

$dom = new DomDocument;
$frag = $dom->createDocumentFragment();
$fragment= $dom->createElement( 'fragment' );
$frag->appendChild( $fragment);

$domNode = $dom2->importNode($frag, true);
$dom2->appendChild( $domNode );

print_r($dom2->saveXML());