Jump to content


Photo

writing tags in xml?


  • Please log in to reply
1 reply to this topic

#1 rune_sm

rune_sm
  • Members
  • PipPip
  • Member
  • 10 posts

Posted 13 October 2006 - 09:11 AM

hey everyone

I'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

#2 dymon

dymon
  • Members
  • PipPipPip
  • Advanced Member
  • 79 posts

Posted 13 October 2006 - 01:19 PM

Hi,

I wrote something like this, but in a existing xml file, here is the 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
	}

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;
Web is the future ... desktop will die ...




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users