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">
<numer_tabeli>184/A/NBP/2021</numer_tabeli>
<data_publikacji>2021-09-22</data_publikacji>
<pozycja>
<nazwa_waluty>bat (Tajlandia)</nazwa_waluty>
<przelicznik>1</przelicznik>
<kod_waluty>THB</kod_waluty>
<kurs_sredni>0,1181</kurs_sredni>
</pozycja>
<pozycja>
<nazwa_waluty id="2">dolar amerykański</nazwa_waluty>
<przelicznik>1</przelicznik>
<kod_waluty>USD</kod_waluty>
<kurs_sredni>3,9460</kurs_sredni>
</pozycja>
</tabela_kursow>
I created attribute with name "id" and value "2" for two Tag elements.
<?php
$doc = new DOMDocument();
$doc->load("kursy_walut.xml");
$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');
}
}
$doc->save('output.xml');
Now I would like to:
- Get only Tag elements which did not contain attribute 'id="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;
$doc3->load('output.xml');
$xpath2 = new DOMXPath($doc3);
$id3 = $xpath2->query('//*/pozycja/nazwa_waluty[@id="2"]');
foreach($id3 as $attr){
$attr->parentNode->removeChild($attr);
}
$doc3->formatOutput = true;
$doc3->save('output3.xml');
Maybe someone can help me with second case?
Thank you.
My Answer:
xml
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:
php
$xml = '
Child 1
Child 2
Child 3
';
$doc = new DOMDocument();
$doc->loadXML($xml);
$xpath = new DOMXPath($doc);
$nodes = $xpath->query('//child[@id="2"]');
foreach ($nodes as $node) {
$node->parentNode->removeChild($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 4477 votesComments