rune_sm Posted October 13, 2006 Share Posted October 13, 2006 hey everyoneI'm making a file, that can write news text into an xml-file. All my text for my page is in the xml-file, and the structure kind of looks like this:<site> <news> </news> <pictures> </pictures> <biography> </biography></site>I have a piece of code (using the dom-functions) and I can easily create new tags within the root-tag. The problem is, that I want to put it inside the news-tag, so I can organize it. I've tried looking around in php.net/dom, but can't really fiure it out. Should be easy anyway. Here is my code: $file_name="text.xml"; $dom = new DomDocument(); $dom->load($file_name); $item = $dom->createElement("item"); $overskrift = $dom->createElement("overskrift", "I am a headline"); $tekst = $dom->createElement("tekst", "I am a text"); $linebreak = $dom->createTextNode(chr(10)); $item->appendChild($overskrift); $item->appendChild($tekst); $item->appendChild($linebreak); $dom->documentElement->appendChild($item); $dom->save($file_name);What I want to do is sort of like $dom->documentElement->news->append....But that doesn't work. Can you help me? - Rune Link to comment https://forums.phpfreaks.com/topic/23831-writing-tags-in-xml/ Share on other sites More sharing options...
dymon Posted October 13, 2006 Share Posted October 13, 2006 Hi,I wrote something like this, but in a existing xml file, here is the code:[code] function create_element($element, $content, $attribute, $attr_val) { global $xml; $elem = $xml->create_element($element); $elem->set_content($content); if ($attribute != '') { $elem->set_attribute($attribute, $attr_val); } return $elem; } $xml = domxml_open_file($path_to_file); $Root = $xml->document_element(); $new_element = $xml->create_element("comment"); //I set two attributes for the new element $new_element->set_attribute("date",$date); $new_element->set_attribute("time",$time); //Append two new childs for the new component (create_element is a function that returns the new created component, look upper) //This thing can help you to add a new element where you want $new_element->append_child(create_element("contr", $_POST['contributor'], '', '')); $new_element->append_child(create_element("string", $_POST['comment'], '', '')); $nodes = $Root -> child_nodes(); foreach ($nodes as $subNode) { if ($subNode -> node_name() == 'comments') $subNode -> append_child($new_element);//here you append the new element to what element you want }[/code]The structure of the xml file is:<main> <comments> //here is where I add the new element <comment date="" time=""> <contr>""</contr> <string>""</string> </comment> </comments></main>Hope it helps; Link to comment https://forums.phpfreaks.com/topic/23831-writing-tags-in-xml/#findComment-108317 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.