dongtangxi1584 2011-10-15 15:41
浏览 45
已采纳

如何将SimpleXML对象转换为PHP数组?

Consider the following code:

$string = '<device>
    <id>1234</id>
    <label>118</label>
    <username>root</username>
    <password>helloWorld</password>
    <hardware>
        <memory>4GB RAM</memory>
        <storage_drives>
            <storage_drive_1>2TB SATA 7,200RPM</storage_drive_1>
            <storage_drive_2>1TB SATA 7,200RPM</storage_drive_2>
            <storage_drive_3>Not Applicable</storage_drive_3>
            <storage_drive_4>Not Applicable</storage_drive_4>
        </storage_drives>
    </hardware>
</device>';
$xml = new SimpleXMLElement($string);

$deviceDetails = Array();
foreach($xml as $element){
    $tag = $element->getName();
    $deviceDetails +=  Array($tag => '$element->$tag)',
        );
    }

Output $detailsDetails array is as follows:

Array
(
    [id] => $element->$tag)
    [label] => $element->$tag)
    [username] => $element->$tag)
    [password] => $element->$tag)
    [hardware] => $element->$tag)
)

which is wrong.

My question is, how to make $element->$tag work?

  • 写回答

3条回答 默认 最新

  • dtyqflrr775518 2011-10-15 16:06
    关注

    Book Of Zeus code wrapped in function to make it work recursively:

    function xml2array($xml)
    {
        $arr = array();
    
        foreach ($xml as $element)
        {
            $tag = $element->getName();
            $e = get_object_vars($element);
            if (!empty($e))
            {
                $arr[$tag] = $element instanceof SimpleXMLElement ? xml2array($element) : $e;
            }
            else
            {
                $arr[$tag] = trim($element);
            }
        }
    
        return $arr;
    }
    
    $xml = new SimpleXMLElement($string);
    print_r(xml2array($xml));
    
    Array
    (
        [id] => 1234
        [label] => 118
        [username] => root
        [password] => helloWorld
        [hardware] => Array
        (
            [memory] => 4GB RAM
            [storage_drives] => Array
            (
                [storage_drive_1] => 2TB SATA 7,200RPM
                [storage_drive_2] => 1TB SATA 7,200RPM
                [storage_drive_3] => Not Applicable
                [storage_drive_4] => Not Applicable
            )
        )
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里