-
- Zhang Ying
- Male
- 28
- tank
- Male
- < ;old>28
Copy code
1) DOMDocument reads xml
-
- $doc = new DOMDocument();
- $doc->load('person.xml'); //Read xml file
- $humans = $doc->getElementsByTagName_r ( "humans" ); //Get the object array of the humans tag
- foreach( $humans as $human )
- {
- $names = $human->getElementsByTagName_r( "name" ); //Get the object array of the tag name
- $name = $names->item(0)->nodeValue; //Get the value in node, such as
- $sexs = $human->getElementsByTagName_r( "sex" );
- $sex = $sexs->item(0)->nodeValue;
- $olds = $human->getElementsByTagName_r( "old" );
- $old = $olds->item(0)- >nodeValue;
- echo "$name - $sex - $oldn";
- }
- ?>
Copy code
2) simplexml reads xml
-
- $xml_array=simplexml_load_file('person.xml'); //Read the data in XML into an array object
- foreach($xml_array as $tmp){
- echo $ tmp->name."-".$tmp->sex."-".$tmp->old."
";
- }
- ?>
Copy code
3 ) Use php regular expressions to remember data
-
-
- $xml = "";
- $f = fopen('person.xml', 'r');
- while( $data = fread( $f, 4096 ) ) {
- $xml .= $data;
- }
- fclose( $f );
- // Read the data above
- preg_match_all( "/(.*?)/s", $xml, $ humans ); //Match the content in the outermost tag
- foreach( $humans[1] as $k=>$human )
- {
- preg_match_all( "/(.*?)
- preg_match_all( "/(.*?)/", $human, $sex ); //Match the gender
- preg_match_all( "/(.*?)/", $human, $old ); //Match age
- }
- foreach($name[1] as $key=> $val){
- echo $val." - ".$sex[$key][1]." - ".$old[$key][1]."
" ;
- }
- ?>
Copy code
4) xmlreader to read 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) { //Determine the node type
- if($i%3){
- echo $reader- >value; //Get the value of node
- }else{
- echo $reader->value."
" ;
- }
- $i++;
- }
- }
- ?>
Copy code
Three, summary
There are many ways to read xml, just to name a few. The above four methods can all read the data in the tag, Zhang Ying. But their testing focus is different. The design focus of the function of reading xml in the first three methods is to read the value in the tag, which is equivalent to The text() method in jquery is different from xmlreader. Its focus is not on reading the value in the tag, but on reading the attributes of the tag and putting all the data to be transmitted in the attributes (but as I mentioned above The method I wrote still takes the value in the tag, because the xml file has been given, and I don’t want to create the xml file again).
Give me an example to explain,
The design focus of xmlreader is to read the value of name sex old in data, but reading the content is more troublesome. It is equivalent to attr(”); in jquery.
|