Click to See Complete Forum and Search --> : creating a valid xml editor thru php


Megatron
03-22-2006, 03:41 PM
i'm trying to do what the title says. basically i have 3 fields that are to be created and stored in a xml file. Those fields being "title", "data" and "url". I have created an editor which can create a txt file called pscontent.txt on the server and can save txt into the said file. I am developing this so that it can create a xml file that will eventually look like this :

<items>

<item>
<title>This is a head</title>
<data>This is a body</data>
<url>my url</url>
</item>
</items>


The code i have is as follows:

<?php
$textFile = "pscontent.xml";
if(isset($_POST['submit'])){ // Saving data
$fh = fopen($textFile,"w");
fwrite($fh,$_POST['fileContent']);
fclose($fh);
echo "Data saved in $textFile";
}
else{ // Show form

$fh = fopen($textFile,"r");
$title = fread ($fh,filesize($textFile));
$data = fread($fh,filesize($textFile));
$url = fread(£fh,filesize($textFile));

fclose($fh);

?>

<form action="<? echo $_SERVER['PHP_SELF']; ?>" method="post">

<p>
Title:
<textarea name="fileContent" cols="50" rows="1"><? echo $title; ?></textarea>
</p>
<p>
URL:
<textarea name="textarea2" cols="50" rows="1"><? echo $url; ?></textarea>
</p>
<p>
Message:
<textarea name="textarea" cols="50" rows="20"><? echo $data; ?></textarea>
</p>
<p>

<input type="submit" name="submit" value="Save" onClick="return confirm('Click OK to save the data')">

</p>
</form>


<?
}



?>

so basically i'm wondering how would i simply wrap the "title" "data" and "url" fields with the required syntax to make it a valid xml file.
Thanks

bokeh
03-22-2006, 06:21 PM
Something like this:<?php

$XML = xmloutput(
array( # this is the XML root element
#first item
array('title' => 'This is the title',
'data' => 'This is the data',
'url' => 'http://url.com/'),
#optionally more items
array('title' => 'This is the title',
'data' => 'This is the data',
'url' => 'http://url.com/')
)
);

file_put_contents('pscontent.txt', $XML);


function xmloutput($input)
{
$XML_document = new DOMDocument('1.0', 'iso-8859-1');
$items = $XML_document->createElement('items');
$XML_document->appendChild($items);
foreach($input as $item_array)
{
$item = $XML_document->createElement('item');
$items->appendChild($item);
foreach($item_array as $key => $value)
{
$$key = $XML_document->createElement($key, $value);
$item->appendChild($$key);
}
}
return $XML_document->saveXML();
}

?>