1

I see many questions about this, but answers are not working for me!

I tried this:

$xml = new DomDocument();
$xml->load('sitemap.xml');
$linkforxml = "https://example.com/" . $filename. ".php";
$xpath = new DOMXPATH($xml);
$nodes = $xpath->query('/urlset/url[loc = "'.$linkforxml.'"]');
foreach($nodes as $node){
$node->parentNode->removeChild($node);
}
$xml->save('sitemap.xml');

And this is what is inside my sitemap file:

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
    <url>
        <loc>https://example.com/test.php</loc>
        <lastmod>2021-06-21T17:31:16+00:00</lastmod>
    </url>
</urlset>

When I run this code the url is still in sitemap file and nothing happen. Anyone can tell me where is my problem?

Yitzhak Khabinsky
  • 18,471
  • 2
  • 15
  • 21
mmdeshoon
  • 11
  • 2
  • Does https://stackoverflow.com/questions/4752942/use-dom-and-xpath-to-remove-a-node-from-a-sitemap-file solve your problem? – Nigel Ren Jun 21 '21 at 14:06
  • While asking a question you need to provide a minimal reproducible example. Please add to your question: (1) input XML, and (2) desired output XML. – Yitzhak Khabinsky Jun 21 '21 at 14:14
  • @NigelRen no I saw it before you say and I use this post to write the code... – mmdeshoon Jun 21 '21 at 14:17
  • The answer to the question I linked to uses namespaces, something your code is missing. If you include the XML it will help to see if this is a problem. – Nigel Ren Jun 21 '21 at 14:19
  • Just tested the code including the namespaces from the other question and it works as expected. – Nigel Ren Jun 21 '21 at 14:23
  • @NigelRen should I load file like this? $DOMfile = new DomDocument();$DOMfile->load('sitemap.xml'); – mmdeshoon Jun 21 '21 at 14:26
  • Loading the file shouldn't matter, it's more the call to `registerNamespace` and then using XPath with that namespace (using sm from the duplicate) `'/sm:urlset/sm:url[sm:loc = "'.$linkforxml.'"]'` – Nigel Ren Jun 21 '21 at 14:27
  • @NigelRen Thanks for the help the problem is fixed ;) – mmdeshoon Jun 21 '21 at 14:31

0 Answers0