John Davidson

php - Remove Child does not contain attribute value


I am practicing with XML DOM PHP parsing. I have such XML file (shorter version):

<?xml version="1.0" encoding="UTF-8"?>
<tabela_kursow typ="A" uid="21a184">
<nazwa_waluty>bat (Tajlandia)</nazwa_waluty>
<nazwa_waluty id="2">dolar amerykański</nazwa_waluty>

I created attribute with name "id" and value "2" for two Tag elements.

$doc = new DOMDocument();
$doc->preserveSpace = false;
$doc->formatOutput = true;

$a = $doc->getElementsByTagName("nazwa_waluty");
$b = count($a);
for ($i=0; $i<$b; $i++){
$c = $a[$i]->childNodes[0]->nodeValue;
if ($c === 'dolar amerykański'){
$a[$i]->setAttribute('id', '2');
if ($c === 'euro'){
$a[$i]->setAttribute('id', '2');

Now I would like to:

  1. Get only Tag elements which did not contain attribute 'id="2"';

  2. Get only Tag elements which contain only 'id="2"'.

For first case I created such code. Don't know exactly how to create second case.

$doc3 = new DOMDocument();
$doc3->preserveWhiteSpace = false;
$xpath2 = new DOMXPath($doc3);
$id3 = $xpath2->query('//*/pozycja/nazwa_waluty[@id="2"]');
foreach($id3 as $attr){
$doc3->formatOutput = true;

Maybe someone can help me with second case?
Thank you.

My Answer:

Child 1
Child 2
Child 3

To remove a child element with a specific attribute value using PHP's DOMDocument, you can use the following code:

$xml = '

Child 1
Child 2
Child 3


$doc = new DOMDocument();

$xpath = new DOMXPath($doc);
$nodes = $xpath->query('//child[@id="2"]');

foreach ($nodes as $node) {

echo $doc->saveXML();

In this code snippet, we first load the XML string into a DOMDocument object. We then use a DOMXPath object to query for the child element with the attribute `id="2"`. We iterate over the resulting nodes and remove each node from its parent node using the `removeChild()` method. Finally, we output the modified XML using the `saveXML()` method.

Rate this post

3 of 5 based on 6283 votes


© 2024 - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us