PHPL using DOM XML Operations xml[Summary]

Source: Internet
Author: User
Tags add array bool copy count create index string version
1, preface   XML tree hierarchy is clear, very suitable as a configuration file. You can use DOM XML to manipulate XML in PHP. This article summarizes PHP using DOM XML to create, add nodes, and query XML files.   2, using DOM XML   XML to divide nodes into elements and text, DOMDocument types are document types, providing member functions and properties for manipulating elements and text.   DOMDocument categories are as follows:   Copy code 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) domcdatasection Createcdatasection (String $data) domcomment createcomment (string $data) domdocumentfragment createdocumentfragment ( void) DomElement createelement (String $name [, String $value]) domelement createelementns (string $namespaceURI, S Tring $qualifiedName [, String $value]) domentityreference createentityreference (string $name) domprocessinginstructi On 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 Load HTML (string $source) bool Loadhtmlfile (string $filename) mixed Loadxml (string $source [, int$options =0]) void normalizedocument (void) bool Registernodeclass (string $baseclass, String $extendedclass) bool R Elaxngvalidate (string $filename) bool Relaxngvalidatesource (string $source) int Save (string $filename [, int $opti ONS]) 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 Xinclud e ([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::issame Node (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)} Copy code element node class DomElement type definition is as follows:   Copying code  1 DomElement extends Domnode { 2/* Properties/ 3 readonly public bool $schemaTypeInfo;  4 Reado nly public string $tagName; &NBSP;5/* Methods/ 6 __construct (String $name [, String $value [, String $namespaceURI]])  7 string Geta Ttribute (String $name)  8 domattr getattributenode (string $name)  9 domattr getattributenodens (String $n Amespaceuri, String $localName) Ten string Getattributens (String $namespaceURI, String $localName) Domnodelist get Elementsbytagname (String $name) domnodelist Getelementsbytagnamens (String $namespaceURI, string $localName) b Ool Hasattribute (string $name) bool Hasattributens (string $namespaceURI, string $localName) bool RemoveaTtribute (string $name) bool Removeattributenode (domattr $oldnode) bool Removeattributens (String $namespaceUR I, String $localName) domattr setattribute (String $name, String $value) domattr Setattributenode (domattr $at TR) domattr Setattributenodens (domattr $attr) void Setattributens (String $namespaceURI, String $qualifiedName , string $value) void Setidattribute (string $name, bool $isId) Setidattributenode (domattr $attr, BOOL $isId) Setidattributens (String $namespaceURI, String $localName, bool $isId)/* Inherited methods/D Omnode domnode::appendchild (Domnode $newnode) domnode domnode::clonenode ([bool $deep]) bool Domnode::hasattri Butes (void) bool Domnode::haschildnodes (void) Domnode Domnode::insertbefore (Domnode $newnode [, Domnode $ref Node]) domnode::isdefaultnamespace bool (string $namespaceURI)-bool Domnode::issamenode (Domnode $node)-Boo L domnode::issupported ( String $feature, String $version) Domnode::lookupnamespaceuri string (string $prefix) Domnode::lookuppre Fix (string $namespaceURI) Domnode void domnode::normalize (void) Notoginseng Domnode::removechild (Domnode $oldnode) D Omnode Domnode::replacechild (Domnode $newnode, Domnode $oldnode) 39} Copy Code text type Domtext is defined as follows:   Copy code Domtext extend s Domcharacterdata {/* Properties/readonly public string $wholeText/* Methods/* __CONSTRUCT ([string $value]) b Ool iswhitespaceinelementcontent (void) domtext splittext (int $offset)/* Inherited methods/void Domcharacterdata: : AppendData (String $data) void Domcharacterdata::d eletedata (int $offset, int $count) void DOMCHARACTERDATA::INSERTD ATA (int $offset, string $data) void Domcharacterdata::replacedata (int $offset, int $count, string $data) string D Omcharacterdata::substringdata (int $offset, int $count)} Copy Code Domnode node is defined as follows:   Copy code domnode {/* Properties * p Ublic 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) Boo L haschildnodes (void) Domnode insertbefore (Domnode $newnode [, Domnode $refnode]) bool Isdefaultnamespace (string $namespaceURI) bool Issamenode (Domnode $node) bool IsSupported (string $feature, String $version) string Lookupname Spaceuri (String $prefix) string LookupPrefix (string $namespaceURI) VoID normalize (void) Domnode removechild (Domnode $oldnode) domnode replacechild (Domnode $newnode, Domnode $oldnode )} Copy Code 3, test program   copy code   1 <?php   2    3 Const INDEX_FILE_NAME = "Student_file_index.xml";   4    5//File Index class   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-&G T;file_name;  17  }  18   Public function get_cur_count ()  19   { 20     return $this-&G T;cur_count;  21  }  22   Public function get_total_count ()  23   { 24     return $this- >total_count;  25  }  26   27   private $file _name;  //filename  28   private $cur _count;  //current record number  29   private $total _count; Total Records  30}  31   32 function Create_file_index (array $params)  33 { 34   $index = NE W 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 &nbs P Create a file element  43   $file = $doc->createelement ("file"); &NBSP;44  //Create an attribute element  45   $name _attr = $doc->createattribute ("name"); &NBSP;46  //Add this property to the file element  47   $file->appendchild ($name _attr);  48   49  //Create a text element  50   $file _name = $doc->createtextnode ($index->get_file_ Name ());  51  //Adding text elementsName_attr properties on  52   $name _attr->appendchild ($file _name);  53   54  //Create a Cur_count element  55   $cur _count = $doc->createelement ("Cur_count", Strval ($index->get_cur_count ()); &NBSP;56  //Add Cur_count to the file element  57   $cur _count = $file->appendchild ($cur _count);  58   59  //Create a Total_count element  60   $total _count = $doc->createelement ("Total_count" ,  61       Strval ($index->get_total_count ())); &NBSP;62  //Add Total_count to the file element  63   $total _count = $file->appendchild ($total _count);  64   65   return $file; &NBSP;66}  67   68 function Create_index_file ($index _file_name, array $params)  69 { 70   Create a document  71   $doc = new DOMDocument ("1.0", "Utf-8");  72  //Create root element  73   $root = $doc->createelement ("index");  74   $root = $doc->appendchild ($root);  75   76  //Create an index structure  77   $index = Create_file_index ($params);  78   $file = Create_file_node ($doc, $index);  79   80  //will file see the root element    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 {&nbsp  //Create a document  89   $doc = new DOMDocument (); &NBSP;90  //loading XML file  91   $doc->load ($index _file_name);  92  //Get index element list  93   $node _list = $doc->getelementsbytagname (' index ');  94  //Get root element  95   $root = $node _list->item (0);  96  //Create an index structure  97   $index = Create_file_index ($params);  98   $file = Create_file_node ($doc, $index);  99  //will file see the root element     $root->appendchild ($file); ->save   $doc ($index _file_name);102} 103  function Traverse_file_index ($index _file_name) {  $file _index = Array ();   $doc = new DOMDocument (); 108   $doc->load ($index _file_name); 109  //Get file Element set   $file _list = $doc->getelementsbytagname (' file ');  //Get Cur_count element Set 112   $cur _count_list = $doc->getelementsbytagname (' Cur_count '); 113  //Get Total_count Element set 114   $total _count_list = $doc->getelementsbytagname (' Total_count ');   for ($i = 0; $i < $file _list->length; $i + +) {116     $index = new File_index (); 117   &NB Sp Gets the Name property value of the file element 118     $file _name = $file _list->item ($i)->attributes->getnameditem ("name")- >nodeValue; 119     $index->set_file_index ($file _name, $cur _count_list->item ($i)->nodevalue, @         $total _count_list->item ($i)->nodevalue); 121     $file _index[$i] = $index; 122  } 123  124   RETUrn $file _index; 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"; ; $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 '] = n; &n Bsp $params [' total_count '] = 33;   echo "Create index file.\n"; 143   Create_index_file ($index _file_name, $params); 144} 145  146//test read XM file 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); 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);   echo "\t\t  "; 156   Echo $index->get_total_count (); 157   echo "\ n"; 158}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.