I have a folder where admin can upload images. Each group of images is related to a specific URL and tracked into a sitemap structure:
Basic XML sitemap
<url>
<loc>URL1</loc>
<image:image>
<image:loc>Image1 URL</image:loc>
<image:caption>Image1 Caption</image:caption>
</image:image>
<image:image>
<image:loc>Image2 URL</image:loc>
<image:caption>Image2 Caption</image:caption>
</image:image>
</url>
<url>
<loc>URL2</loc>
<image:image>
<image:loc>Image3 URL</image:loc>
<image:caption>Image3 Caption</image:caption>
</image:image>
</url>
My goal is to update a specific URL data when admin uploads or delete images related to it. For example, if admin uploads a new Image4
and deletes Image1
from URL1
, the updated sitemap will be:
Updated XML sitemap
<url>
<loc>URL1</loc>
<image:image>
<image:loc>Image2 URL</image:loc>
<image:caption>Image2 Caption</image:caption>
</image:image>
<image:image>
<image:loc>Image4 URL</image:loc>
<image:caption>Image4 Caption</image:caption>
</image:image>
</url>
<url>
<loc>URL2</loc>
<image:image>
<image:loc>Image3 URL</image:loc>
<image:caption>Image3 Caption</image:caption>
</image:image>
</url>
I'm looking for an efficient way to perform updates. I've found this post, but (if I get it correctly) to update URL data, I need to iterate over all URL nodes, find the specific node (i.e. with regular expression) and then update data inside it (i.e. deleting all images and insert new images).
PHP
$dom = new DOMDocument('1.0');
$dom->load('images.xml');
$urls = $dom->getElementsByTagName('url');
foreach($urls as $url)
{
$locs = $url->getElementsByTagName('loc');
$loc = $locs->item(0)->nodeValue;
// check $loc with regular expression and make updates to specific node
}
Honestly, I don't think it's an efficient solution. Is there a fast way to find a specific URL node and update images data inside it?