我编写了一个php代码,用于从XML文件中检索一些数据到一个变量中。
这是XML文件:
<Server>
<Server1>
<ipaddress>10.3.2.0</ipaddress>
<rootpassword>abcd</rootpassword>
<port>22</port>
<autousername>abcd</autousername>
<autopassword>abcd</autopassword>
</Server1>
<Server1>
<ipaddress>10.3.2.1</ipaddress>
<rootpassword>abcd</rootpassword>
<port>22</port>
<autousername>abcd</autousername>
<autopassword>abcd</autopassword>
</Server1>
<Server1>
<ipaddress>10.3.2.2</ipaddress>
<rootpassword>abcd</rootpassword>
<port>22</port>
<autousername>abcd</autousername>
<autopassword>abcd</autopassword>
</Server1>
<Server1>
<ipaddress>10.3.2.3</ipaddress>
<rootpassword>abcd</rootpassword>
<port>22</port>
<autousername>abcd</autousername>
<autopassword>abcd</autopassword>
</Server1>
</Server>
这是PHP代码:
$x = $xmlDoc->getElementsByTagName("ipaddress");
这里我想按索引值显示$x
的内容,类似于
echo $x[0]->nodeValue;
我怎么能那样做呢?
我假设您使用DOMDocument
进行XML解析。当调用getElementsByTagName
时,您将收到DOMNodeList
而不是array
。
DOMNodeList
实现了Traversable
,因此它可以在foreach
循环中使用。
foreach ($x as $item) {
var_dump($item->nodeValue);
}
如果你只想要一个特定的项目,使用item
方法。
$x->item(0)->nodeValue;
您可以像下面这样访问ipaddress
。
$xml = simplexml_load_file("yourxml.xml");
$result = $xml->xpath('//Server1');
foreach($result as $item){
echo "IP Address:".$item->ipaddress
echo "<br/>";
}
演示 。
$xml = simplexml_load_file($path_to_your_xml_file);
foreach($xml->Server1 as $server) {
echo $server->ipaddress . '<br>';
}
或者你可以直接写:
echo $xml->Server1[0]->ipaddress;