加载XML文件和加载内容
问题描述:
您好我正在尝试加载名为articles.xml的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>
但是没有被打印成表..没有任何人有任何想法,为什么?
答
您正在访问(不存在的)属性值,而不是您的内容的节点值。
访问 “标题” 属性的 “条” 的节点上的值:
$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。
+0
谢谢你已经使我傻了。 –
+0
太棒了 - 你会介意将此标记为答案吗?谢谢! – doublesharp
你有'var_dump'ed'$ xml-> RecentArticles-> Article'吗?它是否为'NULL'? –
@u_mulder它不应该,PHP正在访问一个属性而不是节点值。 – doublesharp
已排序现在感谢。 –