2013-05-17 89 views
0

我寫了一個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; 

我該怎麼做?

+0

在這裏你去http://php.net/SimpleXML :) – EaterOfCode

回答

0

我假設你的XML解析使用DOMDocument。當調用getElementsByTagName時,您將收到DOMNodeList而不是array

DOMNodeList implements Traversable因此它可以用於foreach循環。

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

如果你只是想要一個特定項目使用item方法。

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

The demo

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

或者你可以只是做:

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

感謝您的快速重播親愛friend.But我可以通過指數像$ X [0],$ X [顯示值的選項1] like that –

+0

因爲我不想顯示整個元素。 –

+0

@ user2393591是的,你可以。查看編輯。 – xdazz

0

您可以像下面那樣訪問ipaddress

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

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