Getting an array from object using SimpleXMLElement

蹲街弑〆低调 提交于 2019-12-06 03:34:06

When you use print_r on a SimpleXMLElement there comes magic in between. So what you see is not actually what is there. It's informative, but just not the same as with normal objects or arrays.

To answer your question how to iterate:

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

to answer how to convert those into an array:

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

As this would still give you the SimpleXMLElements but you might want to have the values you can either cast each of these elements to string on use, e.g.:

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

or convert the whole array into strings:

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

or alternatively into integers:

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

You can cast the SimpleXMLElement object like so:

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;
}

Or cast the whole thing:

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

Update

Okay, the array_map code just above doesn't really work because it's not strictly an array, you should apply iterator_to_array($message_object->data_id, false) first:

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

See also: @hakre's answer.

You just need to update your foreach like this:

foreach($message_object->data->id as $key => $value) {
    print_r($value);
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!