假设有如下xml文件(/path/to/index.xml):

<?xml version="1.0" encoding="utf-8"?>
<sitemapindex>
    <sitemap>
        <loc>100.xml</loc>
        <lastmod>2020-05-06</lastmod>
    </sitemap>
    <sitemap>
        <loc>101.xml</loc>
        <lastmod>2020-05-06</lastmod>
    </sitemap>
    <sitemap>
        <loc>102.xml</loc>
        <lastmod>2020-05-06</lastmod>
    </sitemap>
</sitemapindex>

新增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();

<!--more-->

输出结果为:

<?xml version="1.0" encoding="utf-8"?>
<sitemapindex>
    <sitemap>
        <loc>100.xml</loc>
        <lastmod>2020-05-06</lastmod>
    </sitemap>
    <sitemap>
        <loc>101.xml</loc>
        <lastmod>2020-05-06</lastmod>
    </sitemap>
    <sitemap>
        <loc>102.xml</loc>
        <lastmod>2020-05-06</lastmod>
    </sitemap>
    <sitemap>
        <loc>103.xml</loc>
        <lastmod>2020-05-07</lastmod>
    </sitemap>
</sitemapindex>

删除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();

输出结果为:

<?xml version="1.0" encoding="utf-8"?>
<sitemapindex>
    <sitemap>
        <loc>100.xml</loc>
        <lastmod>2020-05-06</lastmod>
    </sitemap>
    <sitemap>
        <loc>101.xml</loc>
        <lastmod>2020-05-06</lastmod>
    </sitemap>
    <sitemap>
        <loc>103.xml</loc>
        <lastmod>2020-05-07</lastmod>
    </sitemap>
</sitemapindex>

由于SimpleXML只有新增节点而没有删除节点的方法,所以需要用到dom_import_simplexml将SimpleXMLElement对象转换成DOMElement对象,然后通过removeChild方法删除指定节点。