2

how delete xml block (car) where color is blue?

<?xml version="1.0"?>
<cars>
    <car>
        <color>blue</color>
        <name>jonas</name>
    </car>
    <car>
        <color>green</color>
        <name>123</name>
    </car>
    <car>
        <color>red</color>
        <name>1234</name>
    </car>
</cars>

2 Answers 2

3

Assuming that your XML is contained in a variable $xml, you could use something like the following code:

$dom = new DOMDocument; // use PHP's DOMDocument class for parsing XML

$dom->loadXML($xml); // load the XML

$cars = $dom->getElementsByTagName('cars')->item(0); // store the <cars/> element

$colors = $dom->getElementsByTagName('color'); // get all the <color/> elements

foreach ($colors as $item) // loop through the color elements
    if ($item->nodeValue == 'blue') { // if the element's text value is "blue"
        $cars->removeChild($item->parentNode); // remove the <color/> element's parent element, i.e. the <car/> element, from the <cars/> element
    }
}

echo $dom->saveXML(); // echo the processed XML
Sign up to request clarification or add additional context in comments.

Comments

1

If you have a long xml file, looping through all <car> items may take a while. As an alternative to @lonesomeday's post, this targets the needed elements with XPath:

$domd = new DOMDocument();
libxml_use_internal_errors(true);
$domd->loadXML($xml);
libxml_use_internal_errors(false);

$domx = new DOMXPath($domd);
$items = $domx->query("//car[child::color='blue']");

$cars = $domd->getElementsByTagName("cars")->item(0);
foreach($items as $item) {
  $cars->removeChild($item);
}

3 Comments

+1 Nice point -- you'd need to benchmark to work out what was best depending on the amount of car elements.
One question, though -- why use loadHTML() when the content is XML?
Good point, corrected it. I mostly load html and my hands kinda just typed it ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.