0

My xml file looks like this:

<?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>

Here is the my expected output:

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

And this is my code:

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

The array result I get from var_dump() is null. How can I solve this problem? Please help me out, thanks.

4

1 回答 1

0

您没有显示相关的simpleXMLToArray()功能。因此,我们无法真正判断您的代码有什么问题。

但是将 SimpleXML-Object 转换为数组实际上并不难 - 这是一种方法:

$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,并且您的应用程序具有该文件的读取权限。

于 2013-11-09T15:22:21.567 回答