Tuesday, 6 August 2013

Add new elements to xml file without duplicate

Add new elements to xml file without duplicate

I have two scripts those do the same but with different imput elements. I
want this two scripts write results on same xml file. So in first script i
did this :
$domtree = new DOMDocument('1.0', 'UTF-8');
$xmlRoot = $domtree->createElement("xml");
$xmlRoot = $domtree->appendChild($xmlRoot);
$currentSite = $domtree->createElement("site");
$currentSite = $xmlRoot->appendChild($currentSite);
$site = myfunction("http://site/");
$currentSite->appendChild($domtree->createElement('site',$site));
$site2 = myfunction("http://site2/");
$currentSite->appendChild($domtree->createElement('site2',$site2));
$site3 = myfunction("http://site3/");
$currentSite->appendChild($domtree->createElement('site3',$site3));
header("Content-Type: text/plain");
echo $domtree->save('sites.xml');
In second this :
$domtree = new DomDocument('1.0', 'UTF-8');
if($xml = file_get_contents( 'sites.xml')) {
$domtree->loadXML( $xml, LIBXML_NOBLANKS );
$currentSite = $domtree->getElementsByTagName('site')->item(0);
$site4 = remoteHeader("http://site4/");
$currentSite->appendChild($domtree->createElement('site4',$site4));
$site5 = remoteHeader("http://site5/");
$currentSite->appendChild($domtree->createElement('site5',$site5));
header("Content-Type: text/plain");
echo $domtree->save('sitestatus.xml');
}
When run first script it writes results in xml and replace previous
elements. When run second one it adds results after other correctly but
when run again it not replace previous and so create duplicates. How can i
prevent this ? Thanks.

No comments:

Post a Comment