I'm writing a script that search in multiple XML files for some tag and then if it's find in this tag child named update I need to delete that child and then add it again.
Problem is that I don't understand why it doesn't deletes nodes I want to delete.
Ok so my script (important part I want to discuss) looks like this:
/*
// Pushing all offers from all files to $allOffers array
*/
foreach ($offerFiles as $file)
{
$file = $path . "\\" . $file;
$currentXML = new SimpleXMLElement($file, 0, true);
foreach($currentXML->offer as $offer)
{
if ($offer->number) {
if (!check_if_exists($compiledXML, $offer->number))
{
//array_push($allOffers, $offer);
}
if (check_if_exists($compiledXML, $offer->number) && $offer->action == "update")
{
update_existing_entry($compiledFile, $compiledXML, $offer);
// var_dump($allOffers);
}
}
}
}
/*
// Find and delete existing XML entry offer with update action
*/
function update_existing_entry ($compiledFile, $compiledXML, $parsedOffer) {
$index = 0;
$doc = new DOMDocument();
$doc->load($compiledFile);
$elem = $doc->documentElement;
foreach ($compiledXML->offer as $offer) {
if ((string)$parsedOffer->number === (string)$offer->number) {
$firstchild = $doc->getElementsByTagName('offer')->item($index);
// $firstchild->nodeValue = null;
$elem->removeChild($firstchild);
$doc->save($compiledFile);
//var_dump($parsedOffer->asXML());
}
$index++;
}
var_dump($deleteNodes);
}
Now if I have 2 XML files, 1 with update action, another without it then it works perfect. Problems starts when 1 and 2 files has update action, then I always ends with only one deleted node and error:
Fatal error: Uncaught TypeError: Argument 1 passed to DOMNode::removeChild() must be an instance of DOMNode, null given
Why I can't delete nodes with selected index?
I don't know if it's the best approach, but I have fixed it this way:
function update_existing_entry ($compiledFile, $compiledXML, $parsedOffer) {
$doc = new DOMDocument();
$doc->load($compiledFile);
$node = $doc->documentElement;
foreach ($doc->getElementsByTagName('offer') as $child) {
if (strpos($child->nodeValue, (string)$parsedOffer->number) !== false) {
$node->removeChild($child);
}
}
$doc->save($compiledFile);
}