0

我有一个数组,它从 xml 文件中读取其单元格,我用“for”编写它,但现在因为我不知道我有多少节点我想以它开始和结束的方式编写这个循环xml file.my 代码的结尾是:

$description=array();

for($i=0;$i<2;$i++)
{
$description[$i]=read_xml_node("dscription",$i);
}

和我的 xml 文件:

<eth0>
<description>WAN</description>      
</eth0>
<eth1>
<description>LAN</description>      
</eth1>

在这段代码中,我必须知道“2”,但我想知道一种不需要知道“2”的方法。

4

3 回答 3

1

我不确定您使用的是哪种解析器,但是使用 simplexml 非常容易,所以我使用 simplexml 整理了一些示例代码。

像这样的东西应该可以解决问题:

$xmlstr = <<<XML
<?xml version='1.0' standalone='yes'?>
<node>
<eth0>
<description>WAN</description>      
</eth0>
<eth1>
<description>LAN</description>      
</eth1>
</node>
XML;

$xml = new SimpleXMLElement($xmlstr);

foreach ($xml as $xmlnode) {
 foreach ($xmlnode as $description) {
  echo $description . " ";
 }
}

输出:

WAN LAN  
于 2013-06-12T09:06:16.167 回答
0
$length = count($description);
for ($i = 0; $i < $length; $i++) {
  print $description[$i];
}
于 2013-06-12T09:05:09.980 回答
0

您使用的解析器可能允许您使用一个while循环,该循环将false在到达 XML 文档的末尾时返回。例如:

while ($node = $xml->read_next_node($mydoc)) {
    //Do whatever...
}

如果不存在,您可以尝试将其用作循环count()的第二个参数。for它返回您指定的数组的长度。例如:

for ($i = 0; $i < count($myarray); $i++) {
    //Do whatever...
}
于 2013-06-12T09:05:17.403 回答