如何从@attribute部分获取值?

时间:2013-10-30 19:10:55

标签: php

我无法弄清楚从这个数组中获取这些值。我需要知道代码和名称,以便我的应用程序知道要使用哪一个但我无法从中获取值。有人可以帮帮我吗?这是@attributes中的值。

我顺便使用PHP。

由于

              array(2) {
      [0]=>
      object(SimpleXMLElement)#22 (2) {
        ["@attributes"]=>
        array(2) {
          ["code"]=>
          string(3) "HCD"
          ["name"]=>
          string(31) "HIGH COST DELIVERY REGION SRCHG"
        }
        [0]=>
        string(5) "71.25"
      }
      [1]=>
      object(SimpleXMLElement)#24 (2) {
        ["@attributes"]=>
        array(2) {
          ["code"]=>
          string(3) "HCD"
          ["name"]=>
          string(31) "HIGH COST DELIVERY REGION SRCHG"
        }
        [0]=>
        string(5) "71.25"
      }
    }

2 个答案:

答案 0 :(得分:0)

使用SimpleXML,您可以使用元素来访问XML上的属性,就好像它是一个数组($xml->elementName['attributeName'],或者使用前面给出的->attributes()方法一样。)

例如,给出以下代码:

$xml = new SimpleXMLElement('<root><item foo="bar"></item></root>');

如果我想访问item元素的foo属性,我会像这样访问它:

echo $xml->item['foo'];

但是,有一个问题:返回的值实际上是SimpleXMLElement的一个实例。为了能够存储或使用它,您需要将其转换为基本类型:

echo (string)$xml->item['foo']; // now a string
echo (int)$xml->item['foo']; // now an integer
echo (bool)$xml->item['foo']; // now a boolean

答案 1 :(得分:0)

我自己想出来了。

$xmlResponse->AccessorialCharges->OtherAccessorialCharges[$i]['code'];