How can i append some elements to a particular element in xml using php?

hoslxos

New Member
I am trying to append some data in XML file using PHP.I am searching for a word if it is already present in XML or not.If it's present i only have to append the data to it otherwise i have to create whole element.For this i am using DOMXPath. Code is as follows:\[code\]$fname="ontology.xml"; $xml=new DomDocument;$xml->Load($fname);$xpath = new DOMXPath($xml);$query = '//RelatedTerms/words/word/word_title[.="'.$word.'"]';$entries=$xpath->query($query); if($entries->length!=0){ foreach($entries as $entry) { $wordElement=$xml->getElementsByTagName($entry->parentNode->nodeName)->item(0);//Problem is here even if the <word> is found at the second position it append the element to the first <word> element. $newIsaElement=$xml->createElement('isa'); $newIsaTitleElement=$xml->createElement('isa_title',"sample"); $newRelevanceTitle=$xml->createElement('relevance',"9"); $newIsaElement->appendChild($newIsaTitleElement); $newIsaElement->appendChild($newRelevanceTitle); //$newIsaTitleElement->appendChild($newIsaElement); $wordElement->appendChild($newIsaElement); $xml->save($fname); }}else{ echo "In Here!"; $words=$xml->getElementsByTagName('words')->item(0); $newWordElement=$xml->createElement('word'); $newWordTitleElement=$xml->createElement('word_title',$word); $newIsaElement=$xml->createElement('isa'); $newIsaTitleElement=$xml->createElement('isa_title',"test"); $newRelevanceTitle=$xml->createElement('relevance',"2"); $newWordElement->appendChild($newWordTitleElement); $newIsaElement->appendChild($newIsaTitleElement); $newIsaElement->appendChild($newRelevanceTitle); $newWordElement->appendChild($newIsaElement); $words->appendChild($newWordElement); $xml->save($fname);}\[/code\]I want to add the element to the same element in which the word is found. Please help me through this!Thanks!PS:Here is a format of xml file if u need!\[code\]<RelatedTerms><words> <word> <word_title>algo</word_title> <isa> <isa_title>algorithm</isa_title> <relevance>9</relevance> </isa> <hasa> <hasa_title>Algorithmic Example</hasa_title> <relevance>7</relevance> </hasa> <akindof> <akindof_title>Pseudo Code</akindof_title> <relevance>8</relevance> </akindof> <partof> <partof_title>Data Structures</partof_title> <relevance>9</relevance> </partof> </word> <word> <word_title>algo</word_title> <isa> <isa_title>test</isa_title> <relevance>9</relevance> //instead of adding it here it adds to the above element </isa> </word></words>\[/code\]
 
Back
Top