【问题标题】:How to Access XML attribute using SimpleXML in PHP如何在 PHP 中使用 SimpleXML 访问 XML 属性
【发布时间】:2012-07-12 05:55:31
【问题描述】:

我有一个这样的 XML 文件,我只想获取属性中的值为“1”,PHP 代码应该是什么?提前致谢。

<?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 文档中有 3 个具有“值”属性的 元素。解释代码应该如何选择读取哪一个。

标签: php simplexml


【解决方案1】:
$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;

}

【讨论】:

  • 谢谢你!我只是在几秒钟前尝试过。我也试过你的,两者都有效!这是我的解决方案: $attribute = (string)$xml->node->property->attributes()->value;回声 $attribute;
【解决方案2】:

试试这个:

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

【讨论】:

  • 这就是他为你强调的方式 ;-)
  • @RomanNewaza 我不知道,哈哈:D ...好的更新了答案:-)
猜你喜欢
  • 2012-04-13
  • 2023-03-28
  • 2014-04-26
  • 1970-01-01
  • 2013-12-23
  • 1970-01-01
  • 2017-05-17
  • 1970-01-01
  • 2011-06-05
相关资源
最近更新 更多