【发布时间】:2012-02-25 05:51:36
【问题描述】:
我试图在 php 中解析一个 xml 文档,这有点困难,因为 xml 由对象中的对象组成。这是xml:
<Bars>
<Bar>
<BarName>the bar name</BarName>
<bar_id>0</bar_id>
<Bartenders>
<Bartender><fname>a first name</fname><lname>a last name</lname><imageURL>an image url</imageURL><shift>2</shift></Bartender>
</Bartenders>
<Events>
<Event><EventName> event</EventName><date>08/10/1989</date></Event>
</Events>
<Specials>
<Special> Special 1</Special><Special> Special 2</Special>
</Specials>
</Bar>
很明显,bars xml 元素中有几个这样的“bar”对象。我想弄清楚如何解析这个文件,将内容保存到一个数组中,使用来自 iOS 应用程序的用户输入更新数组,最后将 XML 写回页面。我遇到的问题是,如何将几个“调酒师”、“事件”和“特殊”对象保存到各个酒吧的数组中?我必须在 foreach 数组中创建一个调酒师数组对吗?我是否需要创建一个包含 bartender、event 和特殊数组的 bar 类?
到目前为止,这是我的一段 php 代码:
$bars = $doc->getElementsByTagName("Bar");
foreach($bars as $bar)
{
$barNames = $bar->getElementsByTagName("BarName");
$barName = $barNames->item(0)->nodeValue;
array_push($barNameArray, $barName);
echo "<b>barName:$barName</b><br>";
}
$barsArray = array();
//make any updates to the arrays as needed
for($i = 0; $i < count($barNameArray); $i++) // write an array of bar objects from the arrays created above
如您所见,如果它只是每个条形图的一种类型的元素,我很容易弄清楚。我无法硬编码任何内容,因为我不知道在给定时间发布了多少调酒师、酒吧、特价商品等...感谢您的帮助。
【问题讨论】:
标签: php xml parsing xml-parsing