如何将 SimpleXMLObject 转换为 PHP 数组?
考虑以下代码:
$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
工作?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
试试这个:
这将输出:
或者如果您不喜欢这样,您可以使用 PHP 类,例如: http://www.bin-co.com/php/scripts/xml2array/
或查看 dfsq 答案
Try this:
This will output:
or if you don't like this, you can use a PHP class like: http://www.bin-co.com/php/scripts/xml2array/
or view dfsq answer
宙斯之书 代码封装在函数中以使其递归工作:
Book Of Zeus code wrapped in function to make it work recursively:
试试这个:
Try This: