php - After manipulation of XML file node values with simpleXML, how do I remove the parent when duplicates arise in the node value? -


my xml file looks - want (simplified sake of example ) add 1 every node value , check duplicates. if duplicate node exists in , want remove parent , return unique xml.

<?xml version="1.0" encoding="utf-8"?> <channel> <item>     <gid>1240</gid> </item> <item>     <gid>1440</gid> </item> <item>     <gid>1440</gid> </item> <item>     <gid>246</gid> </item> 

so desired output be:

<?xml version="1.0" encoding="utf-8"?> <channel> <item>     <gid>1241</gid> </item> <item>     <gid>1441</gid> </item> <item>     <gid>247</gid> </item> 

my code looks - manipulation part solved cannot figure out how check if new duplicate , remove parent before returning xml. think storing values array within loop correct after stuck. thankful help.

<?php  $xmllink = 'items.xml';  header("content-type: text/xml");  $xml=simplexml_load_file($xmllink) or die("error: cannot create object");  $xml->channel;  foreach ($xml $anything) {  // find <gid> $newgid = $anything->gid;  // manipulate <gid> $anything->gid = $newgid +1;  // store gid + 1 in array $allgids[] = $newgid;}  echo $xml->asxml();  ?> 

simplexml isn't when want change structure of document.

but can bit of work round. firstly, manipulation on document difficult when trying iterate on @ same time. why i've used xpath list of items , iterate on list. if item there, use unset() remove it. (have more in depth read of remove child specific attribute, in simplexml php full answer how works).

<?php  error_reporting(e_all); ini_set('display_errors', 1);  $xmldoc = <<< xml <?xml version="1.0" encoding="utf-8"?> <channel> <item>     <gid>1240</gid> </item> <item>     <gid>1440</gid> </item> <item>     <gid>1440</gid> </item> <item>     <gid>246</gid> </item> </channel> xml;  $xml = simplexml_load_string($xmldoc); $allgids = []; $items = $xml->xpath("//item"); foreach ($items $item) {      // find <gid>     $newgid = $item->gid;     // manipulate <gid>     $item->gid = $newgid +1;     if ( in_array($newgid, $allgids))   {         unset($item[0]);     }     else    {         // store gid + 1 in array         $allgids[] = (string)$newgid;     } }  echo $xml->asxml(); 

although in example use code string, same apply if loading file are.


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -