1

I'm still really new to using simpleXML with PHP. I'm trying to use simpleXML to remove a segment from a sitemap XML document.

The document looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <url>
        <loc>http://www.test.com/</loc>
        <priority>1.0</priority>
    </url>
    <url>
        <loc>http://www.test.com/test.html</loc>
        <priority>0.6</priority>
    </url>
</urlset>

I would like to provide a specific <loc> web address, search the xml document for that address, then remove the parent <url> element that contains the web address i'm searching for.

Below is the code I though would work but I can't get it to work.

 $xml = simplexml_load_file('path-to-my-sitemap.xml');
 $addressToRemove = "http://www.test.com/test.html";
 $remove = simplexml_load_string("<url><loc>$addressToRemove</loc><priority>0.6</priority></url>");

 xml_remove($xml, $remove);

 $str = $xml->asXML();

 echo $str;
 ?>


 function xml_remove(SimpleXMLElement $xml, SimpleXMLElement $removeFrom) {
     $mainDom = dom_import_simplexml($xml);
     $removeFromDom = dom_import_simplexml($removeFrom);
     $mainDom->removeChild($removeFromDom);
 }

After running my script it should output:

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <url>
        <loc>http://www.test.com/</loc>
        <priority>1.0</priority>
    </url>
</urlset>

Does anyone know what i'm doing wrong here?

Austin
  • 1,619
  • 7
  • 25
  • 51
  • 1
    Have a look at [this post](https://stackoverflow.com/questions/4752942/use-dom-and-xpath-to-remove-a-node-from-a-sitemap-file). Does the job using xpath – Yolo Jul 28 '17 at 17:52
  • thanks....that was it – Austin Jul 28 '17 at 18:21

0 Answers0