delete from xml file with xml dom
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>re开发者_运维知识库d</color>
<name>1234</name>
</car>
</cars>
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
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);
}
精彩评论