Sending input from "GET" to xml file in php

Viewed 68

I am trying to save my input from html file

<form action="skrypt.php" method="GET">
Author: <input type="text" size="20" name="author" /><br>
Message: <input type="text" size="80" name="message" />
<input type="submit" value="Send"/>
</form>

to xml file by using php. My code looks like this:

$author = $_GET["author"];
$message = $_GET["message"];
$file = 'file.xml';

if (!empty($author) && !empty($message)) {
    $xml = simplexml_load_file($file);
    $sxe = simplexml_import_dom($xml);
    $entry = $sxe->addChild("entry");
    $sxe ->addChild("author", $author);
    $sxe ->addChild("message", $message);
    
    $xml->asXml($file);
}
header('location: index.html');
?>

I would like to allow multiple entries. With each input, the new entry would be made and added to the existed file.

<?xml version="1.0"?>
<entry>
    <author>bill</author>
    <message>im sending a message</message>
</entry>
<entry>
    <author>tom</author>
    <message>hello</message>
</entry>

Is it possible to make my output look like the one above? Because I'm getting this one instead.

<?xml version="1.0"?>
<entry>
    <author>bill</author>
    <message>im sending a message</message>
<entry/><author>tom</author><message>hello</message></entry>

After trying to add author and message to $entry rather than to $sxe, I'm getting:

<?xml version="1.0"?>
<entry>
    <author>bill</author>
    <message>im sending a message</message>
<entry>
    <author>tom</author>
    <message>hello</message>
</entry>
</entry>

so I don't think it is the answer. Can someone explain this to me? I would be grateful.

1 Answers

The XML you're trying to create is not valid. An XML document must have only one root node, but you have two (<entry>...</entry> <entry>...</entry>).

You should instead try to generate something like this:

<?xml version="1.0"?>
<entries>
  <entry>
    <author>bill</author>
    <message>im sending a message</message>
  </entry>
  <entry>
    <author>tom</author>
    <message>hello</message>
  </entry>
</entries>

I've not used PHP for XML manipulation before, but I think you'll need something like this:

if (!empty($author) && !empty($message)) {
    try {
      $xml = simplexml_load_file($file);
      $sxe = simplexml_import_dom($xml);
    } catch (exception $e) {
      $sxe = new SimpleXMLElement('<?xml version="1.0"?><entries></entries>');
    }

    // Add new <entry>
    $newEntry = $sxe->addChild("entry");
    $newEntry->addChild("author", $author);
    $newEntry->addChild("message", $message);
    
    $sxe->asXml($file);
}

As comments have mentioned, this fixes a couple of other things:

  • $xml->asXml($file); should be $sxe->asXml($file);
  • $sxe ->addChild("author",.. should be $newEntry->addChild("author",..
Related