加载XML文件并加载内容

时间:2016-12-01 18:38:58

标签: php html xml

您好我正在尝试从名为articles.xml的XML文件中加载内容: 它有和作为元素。

    <?xml version="1.0"?>
<RecentArticles>
  <Article author="The Reddest">
    <Title>Silverlight and the Netflix API</Title>
    <Date>1/13/2009</Date>
    <Description>Description</Description>
    <Link></Link>
  </Article>
  <Article author="The Hairiest">
    <Title>Cake PHP 4 - Saving and Validating Data</Title>
    <Date>1/12/2009</Date>
    <Description>Description</Description>
    <Link></Link>
  </Article>
  <Article author="The Tallest">
    <Title>Silverlight 2 - Using initParams</Title>
    <Date>1/6/2009</Date>
    <Description>Description</Description>
    <Link></Link>
  </Article>
  <Article author="The Fattest">
    <Title>Controlling iTunes with AutoHotkey</Title>
    <Date>12/12/2008</Date>
    <Description>Description</Description>
    <Link></Link>
  </Article>
</RecentArticles>

这是我用来将元素打印到表中的以下PHP代码:

                    <!--Make table and print each xml element into it-->
                <center>
                    <table border="1">
                        <tr>
                            <th>Title</th>
                            <th>Date</th>
                            <th>Description</th>
                            <th>Link</th>

                        </tr>

                        <?php

                            //Load the xml file int a variable for use in the table below.
                            $xml = simplexml_load_file("articles.xml");

                            echo("<tr>");

                            foreach ($xml->RecentArticles->Article as $entry)
                            {

                                $title = $entry['Title']
                                $date = $entry['Date'];
                                $description = $entry['Description'];
                                $link = $entry['Link'];

                                echo("<td>$title</td>");
                                echo("<td>$date</td>");
                                echo("<td>$description</td>");
                                echo("<td>$link</td>");

                            }

                            echo("</tr>");

                        ?>

                    </table>
                </center>

然而,没有任何内容可以打印到表中..有没有人知道为什么?

1 个答案:

答案 0 :(得分:0)

您正在访问(不存在的)属性值,而不是内容的节点值。

访问“文章”节点上的“标题”属性值:

 $title = $entry['Title']

访问“标题”节点值:

 $title = $entry->Title

示例XML:

<RecentArticles>
  <Article author="The Reddest" Title="This is what you are accessing with $entry['Title']">
    <Title>This is what you should be accessing with $entry->Title</Title>
    <Date>1/13/2009</Date>
    <Description>Description</Description>
    <Link></Link>
  </Article>
</RecentArticles>

有关如何访问XML元素的更多信息,请参阅this documentation