假设有如下xml文件(/path/to/index.xml):
100.xml
2020-05-06
101.xml
2020-05-06
102.xml
2020-05-06
新增loc为103.xml的节点
使用SimpleXML的addChild方法:
$xml = simplexml_load_file("/path/to/index.xml");
$sitemap = $xml->addChild('sitemap');
$sitemap->addChild('loc', '103.xml');
$sitemap->addChild('lastmod', '2020-05-07');
echo $xml->asXML();
输出结果为:
100.xml
2020-05-06
101.xml
2020-05-06
102.xml
2020-05-06
103.xml
2020-05-07
删除loc为102.xml的节点
这里需要用到xpath或者循环对象的方法查找指定节点,然后通过dom_import_simplexml转换为DOM对象进行删除:
// xpath查找方法
$xml = simplexml_load_file("/path/to/index.xml");
$res = $xml->xpath("//sitemap[loc='102.xml']");
if (count($res) > 0) {
$dom = dom_import_simplexml($res[0]);
$dom->parentNode->removeChild($dom);
}
echo $xml->asXML();
// 循环对象方法
$xml = simplexml_load_file("/path/to/index.xml");
foreach ($xml->sitemap as $sitemap) {
if ((string)$sitemap->loc == '102.xml') {
$dom = dom_import_simplexml($sitemap);
$dom->parentNode->removeChild($dom);
break;
}
}
echo $xml->asXML();
输出结果为:
100.xml
2020-05-06
101.xml
2020-05-06
103.xml
2020-05-07
由于SimpleXML只有新增节点而没有删除节点的方法,所以需要用到dom_import_simplexml将SimpleXMLElement对象转换成DOMElement对象,然后通过removeChild方法删除指定节点。