首页 > 代码库 > php对xml进行简单的增删改查(CRUD)操作

php对xml进行简单的增删改查(CRUD)操作

假如有下面xml文件:

<span style="font-family:SimSun;"><?xml version="1.0" encoding="UTF-8"?>
<setting>
    <setting1>setting1 value</setting1>
    <setting2>setting2 value</setting2> 
    <setting3>setting3 value</setting3> 
    ....
    ....
    ....
</setting></span>

如何使用php对它进行CRUD?其实像这种简单的xml文件使用SimpleXMl再好不过了。你可以像这样来操作它:

// CREATE
$config = new SimpleXmlElement('<settings/>');
$config->setting1 = 'setting1 value';         
$config->saveXML('config.xml');               

// READ
$config = new SimpleXmlElement('config.xml');
echo $config->setting1;
echo $config->asXml();

// UPDATE
$config->setting1 = 'new value';
$config->setting2 = 'setting2 value';
echo $config->asXml();

// DELETE
unset($config->setting1);
$config->setting2 = NULL;
echo $config->asXML();
unlink('config.xml');

更多详情请移步至PHP官方usage examples 和 API description.

php对xml进行简单的增删改查(CRUD)操作