无法迭代 SimpleXMLElement 对象并插入到数组中

Unable to iterate of SimpleXMLElement objects and insert into array

我有以下 XML:

<channels>
  <channel>
    <name>Channel 1</name>
    <tid>15179</tid>
  </channel>
  <channel>
    <name>Channel 2</name>
    <tid>15177</tid>
  </channel>
  <channel>
    <name>Channel 3</name>
    <tid>15176</tid>
  </channel>
  <channel>
    <name>Channel 4</name>
    <tid>15407</tid>
  </channel>
  <channel>
    <name>Channel 5</name>
    <tid>15175</tid>
  </channel>
  <channel>
    <name>Channel 6</name>
    <tid>15178</tid>
  </channel>
</channels>

并使用 SimpleXMLElement,我得到了这个对象:

SimpleXMLElement Object
(
    [channel] => Array
        (
            [0] => SimpleXMLElement Object
                (
                    [name] => Channel 1
                    [tid] => 15179
                )

            [1] => SimpleXMLElement Object
                (
                    [name] => Channel 2
                    [tid] => 15177
                )

            [2] => SimpleXMLElement Object
                (
                    [name] => Channel 3
                    [tid] => 15176
                )

            [3] => SimpleXMLElement Object
                (
                    [name] => Channel 4
                    [tid] => 15407
                )

            [4] => SimpleXMLElement Object
                (
                    [name] => Channel 5
                    [tid] => 15175
                )

            [5] => SimpleXMLElement Object
                (
                    [name] => Channel 6
                    [tid] => 15178
                )

        )

)

我试图简单地迭代此对象以将通道放入数组中,但无论我如何尝试迭代,我得到的只是 SimpleXMLElement 对象,显然这是不允许的将它们用作数组键。例如,这个代码

$channel_data = new SimpleXMLElement($channel_xml->data);
foreach ($channel_data->children() as $nb_channel) {
  $channel_name = $nb_channel->name;
  $channel_tid = $nb_channel->tid;
  $target_channels[$channel_tid[0]] = $channel_name[0];
}

$channel_name 和 $channel_tid 也作为简单XML元素出现。如果我尝试

foreach ($channel_data->channel as $nb_channel) {
  $channel_name = $nb_channel->name;
  $channel_tid = $nb_channel->tid;
  $target_channels[$channel_tid] = $channel_name;
}

$channel->name 和 $channel->tid 也是简单的XMLElement 对象。

SimpleXMLElement Object
(
    [name] => Channel 1
    [tid] => 15179
)

但试图以

的身份访问它们
   $nb_channel->name;

又给了我一个对象:

SimpleXMLElement Object
(
    [0] => Channel 1
)

迭代 XML 以获取我的数据并将其放入数组的正确方法是什么?

谢谢。

和往常一样,"post a question and then figure out the answer" 原则生效。

诀窍是使用 __toString():

将值转换为字符串
$channel_data = new SimpleXMLElement($channel_xml->data);
foreach ($channel_data->channel as $nb_channel) {
  $channel_name = $nb_channel->name->__toString();
  $channel_tid = $nb_channel->tid->__toString();
  $target_channels[$channel_tid] = $channel_name;
}

一旦我这样做了,我的变量就有了正确的数据,并且我能够填充 $target_channels 数组。