PHP新增、删除xml节点
假设有如下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();
输出结果为:
<?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
方法删除指定节点。