【问题标题】:Getting attribute from simplexml_load_file从 simplexml_load_file 获取属性
【发布时间】:2018-03-21 13:11:19
【问题描述】:

我正在试图弄清楚如何从以下 XML 中加载变量 location、time 和 val。

XML 如下所示:

<root xmlns="">
     <sns id="1" name="Senzor A" type="1" status="0" unit="0" val="4.5" w-min="" w-max=""/>
     <status level="2" location="AAA" time="03/21/2018 14:09:08"/>
</root>

解析后的 XML 如下所示:

object(SimpleXMLElement)#1 (2) {
  ["sns"]=>
  object(SimpleXMLElement)#2 (1) {
    ["@attributes"]=>
    array(8) {
      ["id"]=>
      string(1) "1"
      ["name"]=>
      string(8) "Senzor A"
      ["type"]=>
      string(1) "1"
      ["status"]=>
      string(1) "0"
      ["unit"]=>
      string(1) "0"
      ["val"]=>
      string(3) "4.5"
      ["w-min"]=>
      string(0) ""
      ["w-max"]=>
      string(0) ""
    }
  }
  ["status"]=>
  object(SimpleXMLElement)#3 (1) {
    ["@attributes"]=>
    array(3) {
      ["level"]=>
      string(1) "2"
      ["location"]=>
      string(3) "AAA"
      ["time"]=>
      string(19) "03/21/2018 14:09:08"
    }
  }
}

我很难弄清楚如何导航,所以如果有人能给我一些建议,我将不胜感激。

【问题讨论】:

    标签: php xml simplexml


    【解决方案1】:

    可以使用$tag['attribute_name'] 来使用simpleXML 访问属性。

    可以使用$xml-&gt;tag$xml-&gt;tag-&gt;subtag 访问元素。

    $xml = '<root xmlns="">
    <sns id="1" name="Senzor A" type="1" status="0" unit="0" val="4.5" w-min="" w-max=""/>
    <status level="2" location="AAA" time="03/21/2018 14:09:08"/>
    </root>';
    
    $xml = simplexml_load_string($xml); // or simplexml_load_file("file.xml");
    echo $xml->status['location'];
    echo $xml->status['time'];
    echo $xml->sns['val'];
    

    输出:

    AAA
    03/21/2018 14:09:08
    4.5
    

    【讨论】:

    • 非常感谢!我一直在使事情过于复杂,但在 $xml-> 路径中做了更多级别。
    • @arvestrid 您可以使用$xml-&gt;tag-&gt;subtag 访问它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-31
    • 1970-01-01
    • 1970-01-01
    • 2012-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多