您好,欢迎访问一九零五行业门户网

PHP使用DOM XML操作XML[总结]

1、前言 xml树状层次结构鲜明,非常适合作为配置文件。php中可以使用dom xml来操作xml。本文总结一下php使用dom xml创建、添加节点、查询xml文件。 2、使用dom xml xml中节点分为元素和文本,domdocument类型是文档类型,提供了操作元素和文本的成员函数和属
1、前言
xml树状层次结构鲜明,非常适合作为配置文件。php中可以使用dom xml来操作xml。本文总结一下php使用dom xml创建、添加节点、查询xml文件。
2、使用dom xml
xml中节点分为元素和文本,domdocument类型是文档类型,提供了操作元素和文本的成员函数和属性。
domdocument类如下:
domdocument extends domnode {/* properties */readonly public string $actualencoding ;readonly public domconfiguration $config ;readonly public domdocumenttype $doctype ;readonly public domelement $documentelement ;public string $documenturi ;public string $encoding ;public bool $formatoutput ;readonly public domimplementation $implementation ;public bool $preservewhitespace =true ;public bool $recover ;public bool $resolveexternals ;public bool $standalone ;public bool $stricterrorchecking =true ;public bool $substituteentities ;public bool $validateonparse =false ;public string $version ;readonly public string $xmlencoding ;public bool $xmlstandalone ;public string $xmlversion ;/* methods */__construct ([ string $version [, string $encoding ]] )domattr createattribute ( string $name )domattr createattributens ( string $namespaceuri , string $qualifiedname )domcdatadiv createcdatadiv ( string $data )domcomment createcomment ( string $data )domdocumentfragment createdocumentfragment ( void )domelement createelement ( string $name [, string $value ] )domelement createelementns ( string $namespaceuri , string $qualifiedname [, string $value ] )domentityreference createentityreference ( string $name )domprocessinginstruction createprocessinginstruction ( string $target [, string $data ] )domtext createtextnode ( string $content )domelement getelementbyid ( string $elementid )domnodelist getelementsbytagname ( string $name )domnodelist getelementsbytagnamens ( string $namespaceuri , string $localname )domnode importnode ( domnode $importednode [, bool $deep ] )mixed load ( string $filename [, int $options=0 ] )bool loadhtml ( string $source )bool loadhtmlfile ( string $filename )mixed loadxml ( string $source [, int $options=0 ] )void normalizedocument ( void )bool registernodeclass ( string $baseclass , string $extendedclass )bool relaxngvalidate ( string $filename )bool relaxngvalidatesource ( string $source )int save ( string $filename [, int $options ] )string savehtml ( void )int savehtmlfile ( string $filename )string savexml ([ domnode $node [, int $options ]] )bool schemavalidate ( string $filename )bool schemavalidatesource ( string $source )bool validate ( void )int xinclude ([ int $options ] )/* inherited methods */domnode domnode::appendchild ( domnode $newnode )domnode domnode::clonenode ([ bool $deep ] )bool domnode::hasattributes ( void )bool domnode::haschildnodes ( void )domnode domnode::insertbefore ( domnode $newnode [, domnode $refnode ] )bool domnode::isdefaultnamespace ( string $namespaceuri )bool domnode::issamenode ( domnode $node )bool domnode::issupported ( string $feature , string $version )string domnode::lookupnamespaceuri ( string $prefix )string domnode::lookupprefix ( string $namespaceuri )void domnode::normalize ( void )domnode domnode::removechild ( domnode $oldnode )domnode domnode::replacechild ( domnode $newnode , domnode $oldnode )}
元素节点类domelement类型定义如下:
1 domelement extends domnode { 2 /* properties */ 3 readonly public bool $schematypeinfo ; 4 readonly public string $tagname ; 5 /* methods */ 6 __construct ( string $name [, string $value [, string $namespaceuri ]] ) 7 string getattribute ( string $name ) 8 domattr getattributenode ( string $name ) 9 domattr getattributenodens ( string $namespaceuri , string $localname )10 string getattributens ( string $namespaceuri , string $localname )11 domnodelist getelementsbytagname ( string $name )12 domnodelist getelementsbytagnamens ( string $namespaceuri , string $localname )13 bool hasattribute ( string $name )14 bool hasattributens ( string $namespaceuri , string $localname )15 bool removeattribute ( string $name )16 bool removeattributenode ( domattr $oldnode )17 bool removeattributens ( string $namespaceuri , string $localname )18 domattr setattribute ( string $name , string $value )19 domattr setattributenode ( domattr $attr )20 domattr setattributenodens ( domattr $attr )21 void setattributens ( string $namespaceuri , string $qualifiedname , string $value )22 void setidattribute ( string $name , bool $isid )23 void setidattributenode ( domattr $attr , bool $isid )24 void setidattributens ( string $namespaceuri , string $localname , bool $isid )25 /* inherited methods */26 domnode domnode::appendchild ( domnode $newnode )27 domnode domnode::clonenode ([ bool $deep ] )28 bool domnode::hasattributes ( void )29 bool domnode::haschildnodes ( void )30 domnode domnode::insertbefore ( domnode $newnode [, domnode $refnode ] )31 bool domnode::isdefaultnamespace ( string $namespaceuri )32 bool domnode::issamenode ( domnode $node )33 bool domnode::issupported ( string $feature , string $version )34 string domnode::lookupnamespaceuri ( string $prefix )35 string domnode::lookupprefix ( string $namespaceuri )36 void domnode::normalize ( void )37 domnode domnode::removechild ( domnode $oldnode )38 domnode domnode::replacechild ( domnode $newnode , domnode $oldnode )39 }
文本类型domtext定义如下:
domtext extends domcharacterdata {/* properties */readonly public string $wholetext ;/* methods */__construct ([ string $value ] )bool iswhitespaceinelementcontent ( void )domtext splittext ( int $offset )/* inherited methods */void domcharacterdata::appenddata ( string $data )void domcharacterdata::deletedata ( int $offset , int $count )void domcharacterdata::insertdata ( int $offset , string $data )void domcharacterdata::replacedata ( int $offset , int $count , string $data )string domcharacterdata::substringdata ( int $offset , int $count )}
domnode节点定义如下:
domnode {/* properties */public readonly string $nodename ;public string $nodevalue ;public readonly int $nodetype ;public readonly domnode $parentnode ;public readonly domnodelist $childnodes ;public readonly domnode $firstchild ;public readonly domnode $lastchild ;public readonly domnode $previoussibling ;public readonly domnode $nextsibling ;public readonly domnamednodemap $attributes ;public readonly domdocument $ownerdocument ;public readonly string $namespaceuri ;public string $prefix ;public readonly string $localname ;public readonly string $baseuri ;public string $textcontent ;/* methods */domnode appendchild ( domnode $newnode )domnode clonenode ([ bool $deep ] )bool hasattributes ( void )bool haschildnodes ( void )domnode insertbefore ( domnode $newnode [, domnode $refnode ] )bool isdefaultnamespace ( string $namespaceuri )bool issamenode ( domnode $node )bool issupported ( string $feature , string $version )string lookupnamespaceuri ( string $prefix )string lookupprefix ( string $namespaceuri )void normalize ( void )domnode removechild ( domnode $oldnode )domnode replacechild ( domnode $newnode , domnode $oldnode )}
3、测试程序
1 php 2 3 const index_file_name = student_file_index.xml; 4 5 //文件索引类 6 class file_index 7 { 8 public function set_file_index($file_name, $cur_count, $total_count) 9 { 10 $this->file_name = $file_name; 11 $this->cur_count = $cur_count; 12 $this->total_count = $total_count; 13 } 14 public function get_file_name() 15 { 16 return $this->file_name; 17 } 18 public function get_cur_count() 19 { 20 return $this->cur_count; 21 } 22 public function get_total_count() 23 { 24 return $this->total_count; 25 } 26 27 private $file_name; //文件名 28 private $cur_count; //当前记录数 29 private $total_count; //总记录数 30 } 31 32 function create_file_index(array $params) 33 { 34 $index = new file_index(); 35 $index->set_file_index($params['file_name'], 36 $params['cur_count'], $params['total_count']); 37 return $index; 38 } 39 40 function create_file_node(domdocument $doc, file_index $index) 41 { 42 //创建一个file元素 43 $file = $doc->createelement(file); 44 //创建一个属性元素 45 $name_attr = $doc->createattribute(name); 46 //将该属性添加到file元素上 47 $file->appendchild($name_attr); 48 49 //创建一个文本元素 50 $file_name = $doc->createtextnode($index->get_file_name()); 51 //将文本元素添加name_attr属性上 52 $name_attr->appendchild($file_name); 53 54 //创建一个cur_count元素 55 $cur_count = $doc->createelement(cur_count, strval($index->get_cur_count())); 56 //将cur_count添加到file元素下 57 $cur_count = $file->appendchild($cur_count); 58 59 //创建一个total_count元素 60 $total_count = $doc->createelement(total_count, 61 strval($index->get_total_count())); 62 //将total_count添加到file元素下 63 $total_count = $file->appendchild($total_count); 64 65 return $file; 66 } 67 68 function create_index_file($index_file_name, array $params) 69 { 70 //创建一个文档 71 $doc = new domdocument(1.0, utf-8); 72 //创建根元素 73 $root = $doc->createelement(index); 74 $root = $doc->appendchild($root); 75 76 //创建一个索引结构 77 $index = create_file_index($params); 78 $file = create_file_node($doc, $index); 79 80 //将file看到根元素下 81 $root->appendchild($file); 82 $doc->save($index_file_name); 83 return true; 84 } 85 86 function add_index_file($index_file_name, array $params) 87 { 88 //创建一个文档 89 $doc = new domdocument(); 90 //加载xml文件 91 $doc->load($index_file_name); 92 //获取index元素列表 93 $node_list = $doc->getelementsbytagname('index'); 94 //获取根元素 95 $root = $node_list->item(0); 96 //创建一个索引结构 97 $index = create_file_index($params); 98 $file = create_file_node($doc, $index); 99 //将file看到根元素下 100 $root->appendchild($file);101 $doc->save($index_file_name);102 }103 104 function traverse_file_index($index_file_name)105 {106 $file_index = array();107 $doc = new domdocument();108 $doc->load($index_file_name);109 //获取file元素集合110 $file_list = $doc->getelementsbytagname('file');111 //获取cur_count元素集合112 $cur_count_list = $doc->getelementsbytagname('cur_count');113 //获取total_count元素集合114 $total_count_list = $doc->getelementsbytagname('total_count');115 for ($i = 0; $i $file_list->length; $i++) {116 $index = new file_index();117 //获取file元素的name属性值118 $file_name = $file_list->item($i)->attributes->getnameditem(name)->nodevalue;119 $index->set_file_index($file_name, $cur_count_list->item($i)->nodevalue,120 $total_count_list->item($i)->nodevalue);121 $file_index[$i] = $index;122 }123 124 return $file_index;125 }126 127 /*****************for test*********************/128 $params = array();129 $index_file_name = index_file_name;130 131 if (file_exists($index_file_name)) {132 $params['file_name'] = student_info_2014_02_12;133 $params['cur_count'] = 10;134 $params['total_count'] = 10;135 echo add index to file.\n;136 add_index_file($index_file_name, $params);137 }138 else {139 $params['file_name'] = student_info_2014_02_11;140 $params['cur_count'] = 23;141 $params['total_count'] = 33;142 echo create index file.\n;143 create_index_file($index_file_name, $params);144 }145 146 //测试读取xm文件147 echo read index content from .$index_file_name.\n;148 echo file_name\t\t\tcur_count\ttotal_count.\n;149 $file_index = traverse_file_index($index_file_name);150 foreach($file_index as $index) {151 echo $index->get_file_name();152 echo \t\t ;153 echo $index->get_cur_count();154 echo strval($cur_count);155 echo \t\t ;156 echo $index->get_total_count();157 echo \n;158 }
测试结果如下图所示:
其它类似信息

推荐信息