0

I'm really new to PHP and Im trying to append Nodes to XML using PHP.

This is my comments.php file:

<?php 

$date = "http://jdrag.x10.mx/comments_file.xml";
$xml = simplexml_load_string($data);
$commentt = $xml->addChild("comment");
$name = $_POST["cname"];
$email = $_POST["cemail"];
$comment = $_POST["comment"];
$commentt->addChild("name", $name);
$commentt->addChild("email", $email);
$commentt->addChild("commentInside", $comment);

echo $xml->saveXML();

?>

My comments.html is:

<form action="comments.php" method="post">
Name: <input type="text" name="cname" />
Email: <input type="text" name="cemail" />
Comment: <input type="text" name="comment" />
<input type="submit" />
</form>

As you can see my XML file is simple the comments tag: http://jdrag.x10.mx/comments_file.xml

But when I submit the form I get this error:

Fatal error: Call to a member function addChild() on a non-object in /home/jdragx10/public_html/comments.php on line 5

And because i'm new to PHP I really don't know what it means or how to fix it. Thanks in advance to anyone who can fix my code.

1 Answer 1

1

It looks like you want to be using simplexml_load_file().

The simplexml_load_string() function takes the XML document as a string whereas simplexml_load_file() takes the path to a file containing the XML, as you have.


You also have some problem with variable names, the path to the XML file is held in $date whereas you try to load the XML using the variable $data.


Finally, be sure to turn on (and to the maximum level) error reporting while you are writing your code. The code above gives a notice message ("Notice: Undefined variable: data…"), not just a fatal error message.

Set the values display_errors and error_reporting to On and -1 respectively, either in your php.ini file or using ini_set().

Sign up to request clarification or add additional context in comments.

2 Comments

Question, is it possible to append Nodes and then save it to the actual file. For example, when I submit the form it shows me the results. But I would like it to edit: jdrag.x10.mx/comments_file.xml. As you can see im trying to create a comment system without using database. I will be submitting the comment to the xml file and then use AJAX to receive each comment. But right now its not doing what I want.
Yes, see your other question that got closed and the dozens (if not more) identical questions on the subject here. "Saving" the results is as easy as using asXML(…) instead of saveXML(). Read the manual to find out how.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.