-
-
-
- Zhang Ying
- Male
- 28
-
- Tank
- Male
- 28
1) DOMDocument reads xml
- $ Doc = new DOMDocument ();
- $ Doc-> load ('person. XML'); // read the xml file
- $ Humans = $ doc-> getElementsByTagName_r ("humans"); // get the object array of the humans tag
- Foreach ($ humans as $ human)
- {
- $ Names = $ human-> getElementsByTagName_r ("name"); // an array of objects that obtain the name tag
- $ Name = $ names-> item (0)-> nodeValue; // obtain the value in node, as shown in figure
- $ Sexs = $ human-> getElementsByTagName_r ("sex ");
- $ Sex = $ sexs-> item (0)-> nodeValue;
- $ Olds = $ human-> getElementsByTagName_r ("old ");
- $ Old = $ olds-> item (0)-> nodeValue;
- Echo "$ name-$ sex-$ old \ n ";
- }
- ?>
2) simplexml reading xml
- $ Xml_array = simplexml_load_file ('person. XML'); // read the data in xml to the array object.
- Foreach ($ xml_array as $ tmp ){
- Echo $ tmp-> name. "-". $ tmp-> sex. "-". $ tmp-> old ."
";
- }
- ?>
3) use a php regular expression to record data
- $ Xml = "";
- $ F = fopen ('person. XML', 'r ');
- While ($ data = fread ($ f, 4096 )){
- $ Xml. = $ data;
- }
- Fclose ($ f );
- // Read data above
- Preg_match_all ("/\ (.*?) \ <\/Humans \>/s ", $ xml, $ humans); // match the content in the outermost tag
- Foreach ($ humans [1] as $ k => $ human)
- {
- Preg_match_all ("/\ (.*?) \ <\/Name \>/", $ human, $ name); // match the name
- Preg_match_all ("/\ (.*?) \ <\/Sex \>/", $ human, $ sex); // match the gender
- Preg_match_all ("/\ (.*?) \ <\/Old \>/", $ human, $ old); // match the age
- }
- Foreach ($ name [1] as $ key => $ val ){
- Echo $ val. "-". $ sex [$ key] [1]. "-". $ old [$ key] [1]."
";
- }
- ?>
4) xmlreader reads xml data
- $ Reader = new XMLReader ();
- $ Reader-> open ('person. XML'); // read xml data
- $ I = 1;
- While ($ reader-> read () {// whether to read
- If ($ reader-> nodeType = XMLReader: TEXT) {// judge the node type
- If ($ I % 3 ){
- Echo $ reader-> value; // Get the node value
- } Else {
- Echo $ reader-> value ."
";
- }
- $ I ++;
- }
- }
- ?>
3. there are many methods to read xml. The above four methods can read the data in the tag and display it. however, their test focus is different. the design focus of the function reading xml in the first three methods is to read the values in the tag, which is equivalent to the text () method in jquery, xmlreader is not the same as xmlreader. Instead, xmlreader focuses on reading the values in tags and reading the attributes of tags to transmit data, all are placed in the attribute (but the method I wrote above still takes the value in the tag, because the xml file has been given, and I don't want to get the xml file out ). For example,Xmlreader is designed to read the name sex old value in data, and reading content is troublesome. It is equivalent to attr (") in jquery. |