It is very convenient to read and write xml documents in php5. you can use phpSimpleXML to quickly parse and generate xml files. you can create a SimpleXML object by using the new keyword. the code is as follows :... it is very convenient to read and write xml documents in php5. we can use the php SimpleXML dialog to help us quickly parse and generate xml files.
There are three methods to create a SimpleXML object:
Create with the new keyword, the code is as follows:
$ Xml ="
1
Aaa
16
2
Bbb
26
"; $ Rss = new SimpleXMLElement ($ xml); create with simplexml_load_string (), the code is as follows: $ xml ="
1
Aaa
16
2
Bbb
26
"; // Open-source code phprm.com $ rss = simplexml_load_string ($ xml); the most common method is to create a file using simplexml_load_file () URL. the code is as follows: $ rss = simplexml_load_file (" rss. xml "); or $ rss = simplexml_load_file ("/rss. xml "); // remote documentation
Let's take a look at the example. the code is as follows:
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 the 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 ');
Read xml data: you can directly access a specific element through the element name. all elements in the document are regarded as attributes of the object. the instance code is as follows:
foreach($rss->item as $v){ echo $v->name,'
';//aaa
bbb
} echo $rss->item[1]->age;//26
To modify xml data, you can directly use the object attribute assignment method to directly edit the content of an element. the instance code is as follows:
$ Rss-> item [1]-> name = 'CCC '; // modify the 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. the instance code is as follows:
unset($rss->item[1]); foreach($rss->item as $v){ echo $v->name,'
';//a www.phprm.com aa
}
You can add element data in xml by using the addChild method of the object. the instance code is as follows:
$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
}
Storage of xml data: Use the asXML () method of the object
$ Rss-> asXML ('personinfo. XML'); // store xml data in the personinfo. xml file.
Address:
Reprinted at will, but please attach the article address :-)