There are three ways to create a SimpleXML object:
Create using the New keyword
The code is as follows |
Copy Code |
$xml = "<personinfo><item><id>1</id><name>aaa</name><age>16</age ></item> <item><id>2</id><name>bbb</name><age>26</age></item></ Personinfo> "; $rss =new simplexmlelement ($xml);
|
Using Simplexml_load_string () to create
The code is as follows |
Copy Code |
$xml = "<personinfo><item><id>1</id><name>aaa</name><age>16</age ></item> <item><id>2</id><name>bbb</name><age>26</age></item></ Personinfo> "; $rss =simplexml_load_string ($xml);
|
The most common method is to use Simplexml_load_file () to create from a URL
The code is as follows |
Copy Code |
$rss =simplexml_load_file ("Rss.xml"); Or $rss =simplexml_load_file ("/rss.xml");//Remote document |
Let's look at an example.
The code is as follows |
Copy Code |
<?php $xml = "<personinfo><item><id>1</id><name>aaa</name><age>16</age ></item><item><id>2</id><name>bbb</name><age>26</age></ Item></personinfo> "; $rss =new simplexmlelement ($xml); foreach ($rss->item as $v) { echo $v->name, ' <br/> '; } echo $rss->item[1]->age;//Read data Echo ' $rss->item[1]->name= ' CCC ';//Modify Data foreach ($rss->item as $v) { echo $v->name, ' <br/> ';//aaa <br/> CCC <br/> } Echo ' Unset ($rss->item[1])//Output data foreach ($rss->item as $k => $v) { echo $v->name, ' <br/> ';//aaa <br/> } 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, ' <br/> ';//aaa <br/> ccc_new <br/> } $rss->asxml (' personinfo.xml '); ?>
|
The above example is analyzed below
The code is as follows |
Copy Code |
reading of XML data You can access specific elements directly from the name of the element. All elements in a document are considered to be attributes of that object. foreach ($rss->item as $v) { echo $v->name, ' <br/> ';//aaa <br/> bbb <br/> } Echo $rss->ITEM[1]->AGE;//26 XML data modification, you can directly edit the content of an element directly by using the method of assigning value to the object attribute. $rss->item[1]->name= ' CCC ';//Modify Data foreach ($rss->item as $v) { echo $v->name, ' <br/> ';//aaa <br/> CCC <br/> } You can use the PHP content function unset to remove an element from the tree Unset ($rss->item[1]); foreach ($rss->item as $v) { echo $v->name, ' <br/> ';//a www.111cn.net aa <br/> } XML adds element data and 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, ' <br/> ';//aaa <br/> ccc_ New <br/> } Storage of XML data Use object's Asxml () method $rss->asxml (' personinfo.xml '); Store the XML data in the Personinfo.xml file |