It is very convenient to read and write XML documents in PHP5, and you can use PHP's SimpleXML method to quickly parse and generate XML-formatted files, as illustrated below:
There are three ways of creating a SimpleXML object:
1. create with the new keyword
Copy the Code code as follows:
$xml = " 1 AAA 16
2 bbb ";
$rss =new simplexmlelement ($xml);
2. use Simplexml_load_string () to create
Copy the Code code as follows:
$xml = " 1 AAA 16
2 bbb ";
$rss =simplexml_load_string ($xml);
3. create from a URL using simplexml_load_file ()
Copy the Code code as follows:
$rss =simplexml_load_file ("Rss.xml");
Or:
$rss =simplexml_load_file ("/rss.xml");//Remote document
The concrete examples are as follows:
The
copy Code code is as follows:
!--? php $xml = " 1 AA A 2 bbb + ";
$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 ');
?
Further analysis of the above example is as follows:
Copy the Code code as follows:
reading of XML data
You can access specific elements directly through the name of the element. All elements in the document are considered to be properties of the object.
foreach ($rss->item as $v) {
echo $v->name, '
';//aaa
Bbb
}
Echo $rss->ITEM[1]->AGE;//26
XML data modification, you can directly edit the content of an element by using the method of assigning value of object property
$rss->item[1]->name= ' CCC ';//Modify Data
foreach ($rss->item as $v) {
echo $v->name, '
';//aaa
Ccc
}
You can use PHP content function unset to remove an element from the tree
Unset ($rss->item[1]);
foreach ($rss->item as $v) {
echo $v->name, '
';//a www.jb51.net AA
}
XML adds element data, which can be implemented by 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
}
Storage of XML data
Using the Asxml () method of an object
$rss->asxml (' personinfo.xml ');//store XML data in a Personinfo.xml file
http://www.bkjia.com/PHPjc/825362.html www.bkjia.com true http://www.bkjia.com/PHPjc/825362.html techarticle It is very convenient to read and write XML documents in PHP5, you can use the PHP SimpleXML method to quickly parse and generate XML file, the following example: Create a SimpleXML object has ...