代码之家  ›  专栏  ›  技术社区  ›  Wais Kamal

无法在PHP中循环XML节点

  •  1
  • Wais Kamal  · 技术社区  · 6 年前

    注释.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>
    

    为了循环遍历XML树,我使用了 W3Schools 索引.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>";
      }
    ?>
    

    根据这个例子,我期望:

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

    但是,我有三个错误:

    警告: 192.168.0.1/users/User8650/index.php 2

    simplexml \u load \u file():在

    警告: simplexml加载文件():^in 2

    错误:

    第四个是由于 die() 声明。

    这个例子是错误的还是我哪里做错了?

    1 回复  |  直到 5 年前
        1
  •  5
  •   mayersdesign    6 年前

    您没有有效的 root element 在XML文档中。这将起作用:

    <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>
    
    推荐文章