使用SimpleXMLElement从对象获取数组

时间:2012-12-22 01:57:17

标签: php xml simplexml

我在使用这些对象获取数组时遇到了一些问题。当我print_r()时,将打印以下代码。 $ message_object是对象的名称。

SimpleXMLElement Object
(
    [header] => SimpleXMLElement Object
        (
            [responsetime] => 2012-12-22T14:10:09+00:00
        )

    [data] => SimpleXMLElement Object
        (
            [id] => Array
                (
                    [0] => 65233
                    [1] => 65234
                )

            [account] => Array
                (
                    [0] => 20992
                    [1] => 20992
                )

            [shortcode] => Array
                (
                    [0] => 3255
                    [1] => 3255
                )

            [received] => Array
                (
                    [0] => 2012-12-22T11:04:30+00:00
                    [1] => 2012-12-22T11:31:08+00:00
                )

            [from] => Array
                (
                    [0] => 6121843347
                    [1] => 6121820166
                )

            [cnt] => Array
                (
                    [0] => 24
                    [1] => 25
                )

            [message] => Array
                (
                    [0] => Go tramping wellington 11-30
                    [1] => Go drinking Matakana 2pm
                )

        )

)

我正在尝试使用foreach从对象中获取id数组:

foreach($message_object->data->id AS $id) {
    print_r($id);
}

发送以下回复:

SimpleXMLElement Object ( [0] => 65233 ) SimpleXMLElement Object ( [0] => 65234 )

如何获得[0]的值或者我是否会错误?有没有办法循环结果并获取对象键?

我试图回显$ id [0],但没有返回结果。

3 个答案:

答案 0 :(得分:4)

当你在print_r上使用SimpleXMLElement时,两者之间会产生魔力。所以你看到的实际上并不是什么。它提供了丰富的信息,但与普通对象或数组不同。

回答你的问题如何迭代:

foreach ($message_object->data->id as $id)
{
    echo $id, "\n";
}

回答如何将它们转换为数组:

$ids = iterator_to_array($message_object->data->id, 0);

因为这仍然会给你SimpleXMLElements,但你可能希望拥有这些值,你可以在使用时将每个元素转换为字符串,例如:

echo (string) $ids[1]; # output second id 65234

或将整个数组转换为字符串:

$ids = array_map('strval', iterator_to_array($message_object->data->id, 0));

或者整数:

$ids = array_map('intval', iterator_to_array($message_object->data->id, 0));

答案 1 :(得分:1)

您可以像这样强制转换SimpleXMLElement对象:

foreach ($message_object->data->id AS $id) {
    echo (string)$id, PHP_EOL;
    echo (int)$id, PHP_EOL; // should work too

    // hakre told me that this will work too ;-)
    echo $id, PHP_EOL;
}

或投下整件事:

$ids = array_map('intval', $message_object->data->id);
print_r($ids);

<强>更新

好的,上面的array_map代码并没有真正起作用,因为它不是一个严格的数组,你应该首先应用iterator_to_array($message_object->data_id, false)

$ids = array_map('intval', iterator_to_array$message_object->data->id, false));

另请参阅:@hakre's answer

答案 2 :(得分:0)

您只需要像这样更新您的foreach:

foreach($message_object->data->id as $key => $value) {
    print_r($value);
}