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

标签 php arrays simplexml

考虑以下代码:

$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/

相关文章:

php - jquery-plugin-validation错误信息位置

php - 在 Dockerfile 中指定 umask

php - 使用 simplexml 查找节点是否有 sibling

php - 新手的 Simplexml 和 PHP RSS 提要

PHPUnit - 调用未定义的函数 curl_init() 错误

php - 使用 PayPal 与 Amazon FPS 修改订阅

java - 我的字符切换软件返回相同的答案?

python - 如何检查一个数字是否已经在二维 numpy 数组的第一列中

java - 以递归方式展平包含未知级别的嵌套数组和映射的嵌套映射

php - 添加一个 XML block 作为 SimpleXMLElement 对象的子对象