如何在PHP中引用XML对象内部的XML对象


How do I reference XML objects inside of XML objects in PHP?

我在变量$xml中有一个数据结构,它看起来像这样:

object(SimpleXMLElement)#3 (1) {
  ["release"]=>
  object(SimpleXMLElement)#4 (11) {
    ["@attributes"]=>
    array(1) {
      ["id"]=>
      string(36) "49d996b2-ab53-41bd-8789-3d87938dc07d"
    }
    ["title"]=>
    string(9) "Pinkerton"
    ["status"]=>
    string(8) "Official"
    ["packaging"]=>
    string(10) "Jewel Case"
    ["quality"]=>
    string(6) "normal"
    ["text-representation"]=>
    object(SimpleXMLElement)#5 (2) {
      ["language"]=>
      string(3) "eng"
      ["script"]=>
      string(4) "Latn"
    }
    ["artist-credit"]=>
    object(SimpleXMLElement)#6 (1) {
      ["name-credit"]=>
      object(SimpleXMLElement)#7 (1) {
        ["artist"]=>
        object(SimpleXMLElement)#8 (3) {
          ["@attributes"]=>
          array(1) {
            ["id"]=>
            string(36) "6fe07aa5-fec0-4eca-a456-f29bff451b04"
          }
          ["name"]=>
          string(6) "Weezer"
          ["sort-name"]=>
          string(6) "Weezer"
        }
      }
    }
    ["date"]=>
    string(10) "1996-09-24"
    ["country"]=>
    string(2) "US"
    ["barcode"]=>
    string(12) "720642500729"
    ["asin"]=>
    string(10) "B000000OVP"
  }
}

我该如何在这里引用"威泽"这个名字?还是排序名称?

以下是我尝试过的:

$a = (array)$xml->release['artist-credit']; // nothing
$a = $xml->release['artist-credit']; // nothing
$a = (array)$xml->release->artist-credit; // nothing
var_dump($a);

带连字符的属性需要用大括号括起来,所以如下所示:

$a = $xml->release{'artist-credit'}

将返回xml的艺术家信用部分。因此获得名称:

$name = (string)$xml->release->{'artist-credit'}->{'name-credit'}->artist->name;

请注意,它需要强制转换为字符串,否则您仍然会有一个SimpleXMLElement对象。