1

I have a file where I store comments. The file name is comments.xml:

<?xml version="1.0" encoding="utf-8"?>
<comment>
  <user>User4251</user>
  <date>02.10.2018</date>
  <text>Comment body goes here</text>
</comment>
<comment>
  <user>User8650</user>
  <date>01.10.2018</date>
  <text>Comment body goes here</text>
</comment>

To loop through the XML tree, I am using the example given at W3Schools (with some modifications to the parameters). The code is contained in index.php:

<?php
  $xml = simplexml_load_file("comments.xml") or die("Error: Cannot create object");
  foreach($xml -> children() as $comments) { 
    echo $comments -> user . ", "; 
    echo $comments -> date . ", "; 
    echo $comments -> text . "<br>";
  }
?>

As per the example, I am expecting:

User4251, 02.10.2018, Comment body goes here
User8650, 02.10.2018, Comment body goes here

However, I am getting three errors:

Warning: simplexml_load_file(): comments.xml:7: parser error : Extra content at the end of the document in 192.168.0.1/users/User8650/index.php on line 2

Warning: simplexml_load_file(): in 192.168.0.1/users/User8650/index.php on line 2

Warning: simplexml_load_file(): ^ in 192.168.0.1/users/User8650/index.php on line 2

Error: Cannot create object

The fourth one is due to the die() statement.

Is the example erroneous or am I going wrong somewhere?

3
  • Your missing a container, e.g. 3v4l.org/StGhH. Commented Oct 1, 2018 at 19:03
  • Using $xml -> children() in your loop can mean that it will pick up any child node type, it is usually better to read it with $xml->comment to specify the comment nodes (assuming you have a root node as others have mentioned). Commented Oct 1, 2018 at 19:06
  • Thanks for your advice. Currently I only have <comment> elements, but I am planning to add more later. Commented Oct 1, 2018 at 19:08

1 Answer 1

5

You don't have a valid root element in your XML document. This will work:

<root_example>
 <comment>
   <user>User4251</user>
   <date>02.10.2018</date>
   <text>Comment body goes here</text>
  </comment>
  <comment>
   <user>User8650</user>
   <date>01.10.2018</date>
   <text>Comment body goes here</text>
 </comment>
</root_example>
Sign up to request clarification or add additional context in comments.

3 Comments

Never thought it is as simple as that :)
It never is haha. I guess "comments" would be a decent name for a container here.
Yes, I added it as <comments>.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.