SimpleXML Method of php Read Write XML Interface File Instance Resolution

  • 2021-06-29 10:37:52
  • OfStack

It is very convenient to read and write xml documents in php5. SimpleXML method of php can be used directly to quickly parse and generate xml format files. The following examples are provided:

There are three ways to create an SimpleXML object:

1. Create using the new keyword


$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);

2. Use simplexml_load_string() Creation


$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);

3. Use simplexml_load_file () created from an URL


$rss=simplexml_load_file("rss.xml");
// Or: 
$rss=simplexml_load_file("/rss.xml");// Remote Documents 

Examples are as follows:


<?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 '<hr>';
$rss->item[1]->name='ccc';// Modify data 
foreach($rss->item as $v){
 echo $v->name,' <br /> ';//aaa <br /> ccc <br />
}
echo '<hr>';
unset($rss->item[1]);// output data 
foreach($rss->item as $k=>$v){
 echo $v->name,' <br /> ';//aaa <br />
}
echo '<hr>';
// 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');
?>

Step 1 to analyze the example above as follows:


//xml Reading Data 
// Specific elements can be accessed directly by their name.All elements in the document are considered attributes of the object. 
foreach($rss->item as $v){
    echo $v->name,' <br /> ';//aaa <br /> bbb <br />
}
echo $rss->item[1]->age;//26
//xml Data modifications can be edited directly by using the method of assigning object attributes 1 Contents of elements 
$rss->item[1]->name='ccc';// Modify data 
foreach($rss->item as $v){
    echo $v->name,' <br /> ';//aaa <br /> ccc <br />
}
// Can be used php Content Functions unset To put 1 Elements deleted from tree 
unset($rss->item[1]);
foreach($rss->item as $v){
    echo $v->name,' <br /> ';//a www.ofstack.com aa <br />
}
//xml Add element data, which can be accessed through the object's addChild Method implementation 
$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 />
}
//xml Storage of data 
// Using object asXML() Method 
$rss->asXML('personinfo.xml');// take xml Data stored in personinfo.xml File 


Related articles: