1

I want to remove a node from an XML depending on a child nodes value.

This is my XML structure:

<?xml version="1.0" encoding="UTF-8"?>   
<urlset>
    <url>
        <loc></loc>
        <prority></priority>
        <lastmod></lastmod>
    </url>
    <url>
        <loc></loc>
        <prority></priority>
        <lastmod></lastmod>
    </url>
    <url>
        <loc></loc>
        <prority></priority>
        <lastmod></lastmod>
    </url>
</urlset>

And this is my php:

<?php
    $xml = simplexml_load_string($args);
    $nodes = $xml->children();

    foreach ($nodes as $node) {

        if ((strpos($node->loc, 'cHash') || strpos($node->loc, 'index.php')) !== FALSE) {

             $loc = dom_import_simplexml($node->loc);
             $loc->parentNode->removeChild($loc);

        }

    }

    $args = $xml->asXML();
?>

I search for "cHash" and "index.php" inside the string-value of "loc" and then i want to remove the parent element url (and all children) if this is the case. The condition is working but i cannot select the whole url node to remove. This php snippet only removes the "loc"-node. First i tried it with unset() as many posts suggested, but it did not work. So i got to this, importing it to dom element and then remove it.

I think it should be something like:

$loc = dom_import_simplexml($node->loc);
$loc->parentNode->parentNode->removeChild($loc->parentNode);

or this:

$loc = dom_import_simplexml($node->loc);
$url = dom_import_simplexml($node);
$url->parentNode->removeChild($url);

It´s trial and error, please help!

Mikaelik
  • 355
  • 3
  • 4
  • 12

1 Answers1

0
$url = dom_import_simplexml($node);
$url->parentNode->removeChild($url);

This should give you what you need, it is not working because of your condition :

(strpos($node->loc, 'cHash') || strpos($node->loc, 'index.php')) !== FALSE

Shouldn't it be this ??

(strpos($node->loc, 'cHash') || strpos($node->loc, 'index.php'))

Othman Benchekroun
  • 1,998
  • 2
  • 17
  • 36