Php SimpleXML method reads and writes XML interface file instance parsing. In php5, it is very convenient to read and write xml documents. you can directly use the SimpleXML method of php to quickly parse and generate files in xml format. The following is an example: it is very convenient to create a SimpleXML object and read and write xml documents in php5. you can directly use the SimpleXML method of php to quickly parse and generate files in xml format. The following is an example:
There are three methods to create a SimpleXML object:
1.Create with the new keyword
The code is as follows:
$ Xml =" 1 Aaa 16
2 Bbb 26 ";
$ Rss = new SimpleXMLElement ($ xml );
2.Create with simplexml_load_string ()
The code is as follows:
$ Xml =" 1 Aaa 16
2 Bbb 26 ";
$ Rss = simplexml_load_string ($ xml );
3.Use simplexml_load_file () to create a URL
The code is as follows:
$ Rss = simplexml_load_file ("rss. xml ");
// Or:
$ Rss = simplexml_load_file ("/rss. xml"); // remote documentation
The specific example is as follows:
The code is as follows:
$ Xml =" 1 Aaa 16 2 Bbb 26 ";
$ Rss = new SimpleXMLElement ($ xml );
Foreach ($ rss-> item as $ v ){
Echo $ v-> name ,'
';
}
Echo $ rss-> item [1]-> age; // read data
Echo '';
$ Rss-> item [1]-> name = 'CCC '; // modify data
Foreach ($ rss-> item as $ v ){
Echo $ v-> name ,'
'; // Aaa
Ccc
}
Echo '';
Unset ($ rss-> item [1]); // output data
Foreach ($ rss-> item as $ k => $ v ){
Echo $ v-> name ,'
'; // Aaa
}
Echo '';
// Add data
$ Item = $ rss-> addChild ('ITEM ');
$ Item-> addChild ('id', '3 ');
$ Item-> addChild ('name', 'CCC _ new ');
$ Item-> addChild ('age', '40 ');
Foreach ($ rss-> item as $ k => $ v ){
Echo $ v-> name ,'
'; // Aaa
Ccc_new
}
$ Rss-> asXML ('personinfo. XML ');
?>
The above example is further analyzed as follows:
The code is as follows:
// Read xml data
// You can directly access a specific element through the element name. All elements in the document are considered as attributes of the object.
Foreach ($ rss-> item as $ v ){
Echo $ v-> name ,'
'; // Aaa
Bbb
}
Echo $ rss-> item [1]-> age; // 26
// Modify xml data. you can directly use the object attribute assignment method to directly edit the content of an element.
$ Rss-> item [1]-> name = 'CCC '; // modify data
Foreach ($ rss-> item as $ v ){
Echo $ v-> name ,'
'; // Aaa
Ccc
}
// You can use the php content function unset to delete an element from the tree.
Unset ($ rss-> item [1]);
Foreach ($ rss-> item as $ v ){
Echo $ v-> name ,'
'; // A www.jb51.net aa
}
// Add element data in xml, which can be implemented through the addChild method of the object
$ Item = $ rss-> addChild ('ITEM ');
$ Item-> addChild ('id', '3 ');
$ Item-> addChild ('name', 'CCC _ new ');
$ Item-> addChild ('age', '40 ');
Foreach ($ rss-> item as $ k => $ v ){
Echo $ v-> name ,'
'; // Aaa
Ccc_new
}
// Store xml data
// Use the asXML () method of the object
$ Rss-> asXML ('personinfo. XML'); // store xml data in the personinfo. xml file.
Secret creates a SimpleXML object...