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?

Community
  • 1
  • 1
Wais Kamal
  • 5,858
  • 2
  • 17
  • 36
  • Your missing a container, e.g. https://3v4l.org/StGhH. – user3783243 Oct 01 '18 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). – Nigel Ren Oct 01 '18 at 19:06
  • Thanks for your advice. Currently I only have `` elements, but I am planning to add more later. – Wais Kamal Oct 01 '18 at 19:08

1 Answers1

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>
mayersdesign
  • 5,062
  • 4
  • 35
  • 47