< /article>
*/
/*
Use DOM to copy (clone) the specified node name data into a new XML file, using the relevant knowledge points of three classes: DOMDocument - DOMNodeList - DOMNode
1.DOMNodeList DOMDocument::getElementsByTagName ( string $name )
2.DOMNode DOMNodelist::item ( int $index )
3.DOMNode DOMNode::cloneNode ([ bool $deep ] )
*/
if(!function_exists('l')) {
function l() {
echo '
********************** ***************
';
}
}
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: Specify the name of the copied node element
* @param $file: The name of the newly generated XML file
* @param $attribute: Specify 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
$root->appendChild($title);
if(count($attr)>0 && !empty($attribute)) {
//Create attribute name
$aname = $newdom->createAttribute($attribute);
$title->appendChild($aname);
//Pass attribute value
$aval = $newdom->createTextNode($attr[$i]);
$aname->appendChild($aval);
}
}
$newdom->save($file);
}
}
if(file_exists("test10_12.xml")) {
//Example 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);
//Example 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');
}
?>