简体   繁体   中英

How to Access XML attribute using SimpleXML in PHP

I have a XML file like this and I just want to get the value inside the Property which is "1", what should be the PHP code? Thanks in advance.

<?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>
$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;

}

Try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM