user2012648
user2012648

Reputation: 13

Take form data and write it to XML file

I am trying to take form data (via _POST) and write it to a document using SimpleXML. This is what I have tried and I can't seem to get it to work.

<?php
$title = $_POST['title'];
$link = $_POST['link'];
$description = $_POST['description'];

$rss = new SimpleXMLElement($xmlstr);
$rss->loadfile("feed.xml");

$item = $rss->channel->addChild('item');
$item->addChild('title', $title);
$item->addChild('link', $link);
$item->addChild('description', $description);

echo $rss->asXML();

header("Location: /success.html"); 

  exit;
?>

Any help or a point in the right direction would be much appreciated.

Upvotes: 1

Views: 156

Answers (3)

Laurynas Mališauskas
Laurynas Mališauskas

Reputation: 1919

You use the asXML() function wrong. If you want to write your XML to a file, you must pass a filename parameter to it. Check the SimpleXMLElement::asXML manual

so your code line oututing xml should be changed from

echo $rss->asXML();

to

$rss->asXML('myNewlyCreatedXML.xml');

Upvotes: 1

Loopo
Loopo

Reputation: 2195

There are a few problems with your code

<?php
$title = $_POST['title'];
$link = $_POST['link'];
$description = $_POST['description'];

//$rss = new SimpleXMLElement($xmlstr); // need to have $xmlstr defined before you construct the simpleXML
//$rss->loadfile("feed.xml");
//easier to just load the file when creating your XML object
$rss = new SimpleXML("feed.xml",null,true) // url/path, options, is_url
$item = $rss->channel->addChild('item');
$item->addChild('title', $title);
$item->addChild('link', $link);
$item->addChild('description', $description);


//header("Location: /success.html"); 
//if you want to redirect you should put a timer on it and echo afterwards but by 
//this time if something went wrong there will be output already sent, 
//so you can't send more headers, i.e. the next line will cause an error

header('refresh: 4; URL=/success.html');
echo $rss->asXML(); // you may want to output to a file, rather than the client
// $rss->asXML('outfputfile.xml');
exit;

?>

Upvotes: 0

PravinS
PravinS

Reputation: 2584

rather than using SimpleXMLElement you can create XML directly like this

$xml = '<?xml version="1.0" encoding="utf-8"?>';
$xml .= '<item>';
$xml .= '<title>'.$title.'</title>';
$xml .= '<link>'.$title.'</link>';
$xml .= '<description>'.$title.'</description>';
$xml .= '</item>';
$xml_file = "feed.xml";
file_put_contents($xml_file,$xml);

may this will help you

Upvotes: 0

Related Questions