2012-07-12 51 views
0

我有一個這樣的XML文件,我只想獲得屬性中的值是「1」,應該是PHP代碼?提前致謝。如何使用PHP中的SimpleXML訪問XML屬性

<?xml version="1.0" encoding="UTF-8" ?> 
<nodeInfo> 
<node flag="128"> 
<address>18 F5 40 1</address> 
<name>iMeterSolo</name> 
<type>9.7.135.92</type> 
<enabled>true</enabled> 
<deviceClass>0</deviceClass> 
<wattage>0</wattage> 
<dcPeriod>0</dcPeriod> 
<pnode>18 F5 40 1</pnode> 
<property id="ST" ***value="1"*** formatted="1" uom="W" /> 
</node> 
<properties> 
<property id="ST" value="1" formatted="1" uom="W" /> 
<property id="TPW" value="226" formatted="226" uom="kWs" /> 
</properties> 
</nodeInfo> 
+0

有3個元素與XML文檔中的 「值」 屬性。解釋代碼應該如何選擇閱讀哪一個。 – LisMorski 2012-07-12 06:01:08

回答

0
$string = '<?xml version="1.0" encoding="UTF-8" ?> 
    <nodeInfo> 
     <node flag="128"> 
      <address>18 F5 40 1</address> 
      <name>iMeterSolo</name> 
      <type>9.7.135.92</type> 
      <enabled>true</enabled> 
      <deviceClass>0</deviceClass> 
      <wattage>0</wattage> 
      <dcPeriod>0</dcPeriod> 
      <pnode>18 F5 40 1</pnode> 
      <property id="ST" value="1" formatted="1" uom="W" /> 
     </node> 
     <properties> 
      <property id="ST" value="1" formatted="1" uom="W" /> 
      <property id="TPW" value="226" formatted="226" uom="kWs" /> 
     </properties> 
</nodeInfo>'; 

$xml = simplexml_load_string($string); 

echo (string) $xml->node->property->attributes()->value.PHP_EOL; 

foreach($xml->properties->property as $element) { 

    $attr = $element->attributes(); 

    echo (string) $attr->value.PHP_EOL; 

} 
+0

謝謝你!幾秒前我剛剛嘗試過。我也試過你們,都是這樣的!這裏是我的解決方案: $ attribute =(string)$ xml-> node-> property-> attributes() - > value; echo $ attribute; – user1519773 2012-07-12 06:11:27

0

試試這個:

<?php 
    $xml = '<nodeInfo><node flag="128"> 
    <address>18 F5 40 1</address> 
    <name>iMeterSolo</name> 
    <type>9.7.135.92</type> 
    <enabled>true</enabled> 
    <deviceClass>0</deviceClass> 
    <wattage>0</wattage> 
    <dcPeriod>0</dcPeriod> 
    <pnode>18 F5 40 1</pnode> 
    <property id="ST" value="1" formatted="1" uom="W" /> 
    </node> 
    <properties> 
    <property id="ST" value="1" formatted="1" uom="W" /> 
    <property id="TPW" value="226" formatted="226" uom="kWs" /> 
    </properties> 
    </nodeInfo>'; 
    $xmlObj = simplexml_load_string($xml); 
    $arrXml = array($xmlObj); 
    echo $arrXml[0]->node->property->attributes()->value; 
+0

這是他如何突出顯示,爲你;-) – 2012-07-12 06:14:54

+0

@RomanNewaza我不知道,LOL:D ...確定更新了答案:-) – Vimalnath 2012-07-12 06:44:41