Copy codeThe Code is as follows:
<? Php
/*
<? Xml version = "1.0" encoding = "UTF-8"?>
<Article>
<Item>
<Title name = "t1"> </title>
<Content> content1 </content>
<Pubdate> 2009-10-11 </pubdate>
</Item>
<Item>
<Title name = "t2"> title2 </title>
<Content> content2 </content>
<Pubdate> 2009-11-11 </pubdate>
</Item>
</Article>
*/
/*
Using DOM to copy (clone) the data of a specified node name to a New XML file, three knowledge points are used: DOMDocument-DOMNodeList-DOMNode
1. DOMNodeList DOMDocument: getElementsByTagName (string $ name)
2. DOMNode DOMNodelist: item (int $ index)
3. DOMNode: cloneNode ([bool $ deep])
*/
If (! Function_exists ('l ')){
Function l (){
Echo '<br/> ******************************* <br /> ';
}
}
If (! Function_exists ('cp _ xml ')){
/*
* Copy the specified node element information to the New XML file.
* @ Param $ dom: DOM object of the source XML file
* @ Param $ newdom: DOM object of the New XML file
* @ Param $ node: Specifies the name of the copied node element.
* @ Param $ file: New XML file name
* @ Param $ attribute: Specifies the attribute name of the copied node element.
* @ Return void
*/
Function cp_xml ($ dom, $ newdom, $ node, $ file, $ attribute = ''){
$ Contents = $ dom-> getElementsByTagName ($ node );
$ Clone = array ();
$ Attr = array ();
For ($ I = 0; $ I <$ contents-> length; $ I ++ ){
$ Node = $ contents-> item ($ I );
If ($ node-> hasAttributes ()&&! Empty ($ attribute )){
$ Attr [] = $ node-> getAttribute ($ attribute );
}
$ Clone [] = $ node-> cloneNode (true );
}
Var_dump ($ attr );
$ Root = $ newdom-> createElement ('root ');
$ Newdom-> appendChild ($ root );
For ($ I = 0; $ I <count ($ clone); $ I ++ ){
$ Title = $ newdom-> createElement ($ clone [$ I]-> nodeName, $ clone [$ I]-> nodeValue );
$ Root-> appendChild ($ title );
If (count ($ attr)> 0 &&! Empty ($ attribute )){
// Create an attribute name
$ Aname = $ newdom-> createAttribute ($ attribute );
$ Title-> appendChild ($ aname );
// Pass the attribute value
$ Aval = $ newdom-> createTextNode ($ attr [$ I]);
$ Aname-> appendChild ($ aval );
}
}
$ Newdom-> save ($ file );
}
}
If (file_exists ("test10_12.xml ")){
// Instance 1
$ Dom = new DOMDocument ();
$ Newdom = new DOMDocument ('1. 0', 'utf-8 ');
$ Dom-> load ("test10_12.xml ");
$ Node = 'content ';
$ File = '11 _ 1. xml ';
Cp_xml ($ dom, $ newdom, $ node, $ file );
// Instance 2
$ Dom = new DOMDocument ();
$ Newdom = new DOMDocument ('1. 0', 'utf-8 ');
$ Dom-> load ("test10_12.xml ");
$ Node = 'title ';
$ File = '11 _ 2. xml ';
Cp_xml ($ dom, $ newdom, $ node, $ file, $ attribute = 'name ');
}
?>