XML到表格式。我只得到一张桌子。我需要显示两个表,怎么做?

时间:2016-12-20 20:06:08

标签: php xml html-table

我只得到一张桌子。我需要显示两个表,怎么做?

<?xml version="1.0"?>
<books>
  <book> 
    <title>Heart of a Dog</title>
    <author>Mikhail Bulgakov</author>
  </book>
  <book> 
    <title>Postmortem</title>
    <author>Patricia Cornwell</author>
  </book>
</books>

也许错误的 foreach循环构造?

 <?php
 $xml = simplexml_load_file('books.xml');
 foreach ($xml as $x) {
    $title = $x->title;
    $author = $x->author;
 }
 ?>

<table width="200" border="1" cellspacing="0" cellpadding="5">
    <tr>
        <td><?php echo "Title: ".$title; ?></td>
    </tr><tr>
        <td><?php echo "Author: ".$author; ?></td>
    </tr>
</table>

1 个答案:

答案 0 :(得分:0)

根据您的输出 你的代码是正确的,除了你需要将你的表放在你的循环中并为每本书生成表。

<?php
 $xml = simplexml_load_file('books.xml');
 foreach ($xml as $x) {
    $title = $x->title;
    $author = $x->author;
    ?>
    <table style="margin-top:10px;" width="200" border="1" cellspacing="0" cellpadding="5">
    <tr>
        <td><?php echo "Title: ".$title; ?></td>
    </tr>
    <tr>
        <td><?php echo "Author: ".$author; ?></td>
    </tr>
    </table>
    <?php
 }
 ?>