从 xml 文件创建一个数组


Create an array from xml file

我的xml文件看起来像这样:

<?xml version="1.0" encoding="utf-8"?>
<root>
  <item>
    <Post>
      <id><![CDATA[1]]></id>
      <title><![CDATA[The title]]></title>
      <body><![CDATA[This is the post body.]]></body>
      <created><![CDATA[2008-07-28 12:01:06]]></created>
      <modified><![CDATA[]]></modified>
    </Post>
  </item>
  <item>
    <Post>
      <id><![CDATA[2]]></id>
      <title><![CDATA[A title once again]]></title>
      <body><![CDATA[And the post body follows.]]></body>
      <created><![CDATA[2008-07-28 12:01:06]]></created>
      <modified><![CDATA[]]></modified>
      <item>
        <item><![CDATA[fdgs]]></item>
      </item>
    </Post>
  </item>
  <item>
    <Post>
      <id><![CDATA[3]]></id>
      <title><![CDATA[Title strikes back]]></title>
      <body><![CDATA[This is really exciting Not.]]></body>
      <created><![CDATA[2008-07-28 12:01:06]]></created>
      <modified><![CDATA[]]></modified>
    </Post>
  </item>
</root>

这是我的预期输出:

Array(
0=>Array(
    'Post'=>Array(
        'id'=>1, 
        'title'=>'The title', 
        'body'=>'This is the post body.', 
        'created'=>'2008-07-28 12:01:06', 
        'modified'=>'',)
        ), 
1=>Array(
    'Post'=>Array(
        'id'=>2, 
        'title'=>'A title once again', 
        'body'=>'And the post body follows.', 
        'created'=>'2008-07-28 12:01:06', 
        'modified'=>'', 
        array('fdgs'),)
        ), 
2=>Array(
    'Post'=>Array(
        'id'=>3, 
        'title'=>'Title strikes back', 
        'body'=>'This is really exciting Not.', 
        'created'=>'2008-07-28 12:01:06', 
        'modified'=>'',)
        ),
);

这是我的代码:

$xml=new Xml2Array();
        $xmlData = simplexml_load_file('d:''xmlfile''Array2XmlExampleData.xml');
        $expectedResult=$xml->simpleXMLToArray($xmlData);
        var_dump($expectedResult);

我从 var_dump() 得到的数组结果为空。如何解决这个问题?请帮帮我,谢谢。

您没有显示相关的simpleXMLToArray()函数。所以我们无法真正判断你的代码出了什么问题。

但是将 SimpleXML 对象转换为数组实际上并不难 - 这里有一种方法可以做到这一点:

$array = json_decode( json_encode( (array) $xmlData ), true);

将给定的 XML 转换为数组。但是要使其在您的情况下工作,您需要确保使用 LIBXML_NOCDATA 标志加载数据(请参阅文档):

$xmlData = simplexml_load_file('d:''xmlfile''Array2XmlExampleData.xml', 'SimpleXMLElement', LIBXML_NOCDATA);

现在,您只需加载XML,遍历<item>-tags并将它们转换为数组:

$xmlData = simplexml_load_file(
      'd:''xmlfile''Array2XmlExampleData.xml', 
      'SimpleXMLElement', 
      LIBXML_NOCDATA
);
$results = [];
foreach($xmlData->item as $item)
{
  $results[] = json_decode(json_encode((array)$item), true);
}

这是一个工作示例。当然,您需要添加清理逻辑来过滤不需要的元素或进行一些格式化。但你明白了。

此外,请确保正确加载 xml,并且应用程序具有文件的读取权限。