gpt4 book ai didi

php - 如何将 SimpleXMLObject 转换为 PHP 数组?

转载 作者:IT王子 更新时间:2023-10-29 00:16:14 24 4
gpt4 key购买 nike

考虑以下代码:

$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)',
);
}

输出$detailsDetails数组如下:

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

这是错误的。

我的问题是,如何让 $element->$tag 工作?

最佳答案

试试这个:

$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 = json_decode(json_encode((array) simplexml_load_string($string)), 1);

这将输出:

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
)

)

)

或者如果您不喜欢这样,您可以使用像这样的 PHP 类:http://www.bin-co.com/php/scripts/xml2array/

或查看dfsq答案

关于php - 如何将 SimpleXMLObject 转换为 PHP 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7778814/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com