php将XML对象转换成数组的例子

发布时间:2020-05-08编辑:脚本学堂
本文介绍下,在php编程中,将xml对象转换成php数组的方法,分享一个实例代码,供大家学习参考。

得到一个xml型的对象:
 

复制代码 代码示例:
$resp = $this->c->execute($req, $sessionKey);//获得xml对象
$items=$resp->items;

读取对象的值,就用$items->item,或$items->item->price。

php提供了array方法将对象转换成数组,只需将转换数组的对象前面加上(array)即可。

例如,将$items->item(有很多item的对象)转换成数组:
 

复制代码 代码示例:
foreach ($items->item as $item){
         $goods[]=(array)$item;
}
 

$goods即为一个php数组了。

转换前:
 

复制代码 代码示例:
SimpleXMLElement Object
(
    [cid] => 50003793
    [modified] => 2013-04-18 17:16:25
    [nick] => qq307819623
    [price] => 200.00
    [title] => Nokia N97全新行货
)
SimpleXMLElement Object
(
    [cid] => 50024921
    [modified] => 2013-04-18 16:58:06
    [nick] => qq307819623
    [pic_url] => http://www.jb200.com/i2/19325021969376698/T1hc87XB8hXXXXXXXX_!!0-item_pic.jpg
    [price] => 888888.00
    [title] => 刘俊仲
)
SimpleXMLElement Object
(
    [cid] => 1512
    [modified] => 2013-04-18 16:56:46
    [nick] => qq307819623
    [pic_url] => http://www.jb200.com/i2/19325023881567971/T1hc87XB8hXXXXXXXX_!!0-item_pic.jpg
    [price] => 323232.00
    [title] => 二手你好
)
SimpleXMLElement Object
(
    [cid] => 50012166
    [modified] => 2013-04-18 15:10:07
    [nick] => qq307819623
    [pic_url] => http://www.jb200.com/i2/19325034513112454/T1hc87XB8hXXXXXXXX_!!0-item_pic.jpg
    [price] => 32.00
    [title] => 放大率拉德斯基分拉沙德疯了似的看法拉斯法
)

转换后:
 

复制代码 代码示例:
Array
(
    [0] => Array
        (
            [cid] => 50003793
            [modified] => 2013-04-18 17:16:25
            [nick] => qq307819623
            [price] => 200.00
            [title] => Nokia N97全新行货
        )
 
    [1] => Array
        (
            [cid] => 50024921
            [modified] => 2013-04-18 16:58:06
            [nick] => qq307819623
            [pic_url] => http://www.jb200.com/i2/19325021969376698/T1hc87XB8hXXXXXXXX_!!0-item_pic.jpg
            [price] => 888888.00
            [title] => 刘俊仲
        )
 
    [2] => Array
        (
            [cid] => 1512
            [modified] => 2013-04-18 16:56:46
            [nick] => qq307819623
            [pic_url] => http://www.jb200.com/i2/19325023881567971/T1hc87XB8hXXXXXXXX_!!0-item_pic.jpg
            [price] => 323232.00
            [title] => 二手你好
        )
 
    [3] => Array
        (
            [cid] => 50012166
            [modified] => 2013-04-18 15:10:07
            [nick] => qq307819623
            [pic_url] => http://www.jb200.com/i2/19325034513112454/T1hc87XB8hXXXXXXXX_!!0-item_pic.jpg
            [price] => 32.00
            [title] => 放大率拉德斯基分拉沙德疯了似的看法拉斯法
        ) 
)