如何从对象php中获取属性


How get attributes from object php?

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

  • 代码
  • 字符串(值)

我试图从$cbr_xml->course[0]:中获取代码属性

 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'];