如何从对象 php 获取属性?

How get attributes from object php?

有来自 XML 的对象,我尝试获取每个项目的属性:

我试图从 $cbr_xml->course[0]:

获取 code 属性
 foreach($cbr_xml->course[0] as $key => $currency){
      var_dump($currency['code'][$key]); // get
}

循环var_dump($currency);之后的对象:

object(SimpleXMLElement)#321 (2) {
  ["@attributes"]=>
  array(1) {
    ["code"]=>
    string(3) "USD"
  }
  [0]=>
  string(7) "11.1000"
}
object(SimpleXMLElement)#324 (2) {
  ["@attributes"]=>
  array(1) {
    ["code"]=>
    string(3) "EUR"
  }
  [0]=>
  string(7) "12.5763"
}

您可以通过以下代码获取属性:

foreach($cbr_xml->course[0] as $single_element){
  foreach($single_element->attributes() as $attr_key=>$attr_value) {
    if($attr_key=='code') { echo $attr_value; }
  }
}

您需要访问 @attributes

像这样:

$currency->attributes()['code']

只需使用数组解引用:

echo $currency['code'];