不按索引显示数组元素

I wrote a php code for retrieving some data from a XML file into a variable.

This is the XML file:

<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>

This is the PHP code:

$x = $xmlDoc->getElementsByTagName("ipaddress");

Here i want to display the content of $x by index value, something like

echo $x[0]->nodeValue;

How could I do that?

I assume you used DOMDocument for the XML parsing. When invoking getElementsByTagName you will receive a DOMNodeList not an array.

DOMNodeList implements Traversable so it can be used in foreach loops.

foreach ($x as $item) {
    var_dump($item->nodeValue);
}

If you just want a specific item use the item method.

$x->item(0)->nodeValue;

The demo.

$xml = simplexml_load_file($path_to_your_xml_file);
foreach($xml->Server1 as $server) {
  echo $server->ipaddress . '<br>';
}

Or you could just do:

echo $xml->Server1[0]->ipaddress;

You can access ipaddress like below.

$xml = simplexml_load_file("yourxml.xml");
$result = $xml->xpath('//Server1');

foreach($result as $item){
    echo "IP Address:".$item->ipaddress
    echo "<br/>";
}