使用PHP将xml结果输出到表中

时间:2014-03-10 16:37:47

标签: php xml

我已成功组建一个PHP脚本来读取xml文件的内容并将结果输出到HTML页面。我唯一要努力解决的问题是如何将输出格式化为表格。

PHP脚本:

<?php
    // Loading the XML file
    $xml = simplexml_load_file("ftpxml.xml");
    echo "<h2>".$xml->getName()."</h2><br />";
    foreach($xml->children() as $ftpxml)
    {
        echo "PID : ".$ftpxml->attributes()->pid."<br />";
        echo "Account : ".$ftpxml->attributes()->account." <br />";
        echo "Time : ".$ftpxml->attributes()->time." <br />";
        echo "<hr/>";
    }
?>

HTML结果:

PID : 279
Account : account001 
Time : 137 
----------------------------------------------------------------
PID : 268
Account : account002 
Time : 301 
----------------------------------------------------------------
PID : 251
Account : account003 
Time : 5 
----------------------------------------------------------------

我迷失了如何显示每个表格标题和相应的内容。我是PHP的新手,所以请指导我,或者如果已经回答了其他地方,请提供链接,以便我可以从中学习。

由于

3 个答案:

答案 0 :(得分:4)

<?php
// Loading the XML file
$xml = simplexml_load_file("ftpxml.xml");
echo "<h2>".$xml->getName()."</h2><br />";
echo "<table>";
    foreach($xml->children() as $ftpxml)
    {
        echo "<tr><td>PID : ".$ftpxml->attributes()->pid."</td></tr>";
        echo "<tr><td>Account : ".$ftpxml->attributes()->account." </td></tr>";
        echo "<tr><td>Time : ".$ftpxml->attributes()->time." </td></tr>";
    }
echo "</table>";
?>

答案 1 :(得分:1)

    echo '<table>';
    echo '<thead><tr><th>PID</th><th>Account</th><th>Time</th></tr></thead><tbody>';
    foreach($xml->children() as $ftpxml)
    {
        echo '<tr>';
        echo "<td>PID : ".$ftpxml->attributes()->pid."</td>";
        echo "<td>Account : ".$ftpxml->attributes()->account."</td>";
        echo "<td>Time : ".$ftpxml->attributes()->time." </td>";
        echo '</tr>';
    }
    echo '</tbody></table>';

答案 2 :(得分:0)

我假设你想在表格中设置不同的字段:

// Loading the XML file
$xml = simplexml_load_file("ftpxml.xml");
echo "<h2>".$xml->getName()."</h2><br />";
echo "<table><thead><tr><th>PID</th><th>Account</th><th>Time</th></tr></thead><tbody>";
foreach($xml->children() as $ftpxml)
{
  echo '<tr>';
  echo '<td>' . $ftpxml->attributes()->pid . "</td>";
  echo '<td>' . $ftpxml->attributes()->account . "</td>";
  echo '<td>' . $ftpxml->attributes()->time . "</td>";
  echo '</tr>';
}
echo '</tbody></table>';