将数组转换为特定的XML

时间:2013-06-23 15:23:39

标签: xml cakephp

我想转换这个给定的数组

array(
    'podcast' => array(
        (int) 0 => array(
            'Podcast' => array(
                'id' => '2',
                'xmlurl' => 'http://test2.com'
            )
        ),
        (int) 1 => array(
            'Podcast' => array(
                'id' => '4',
                'xmlurl' => 'http://test4.com'
            )
        )
    )
)

使用CakePHP 2.3.6进入此字符串:

<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>
<opml version="2.0">
    <head></head>
    <body>
        <outline xmlUrl="http://test2.com" />
        <outline xmlUrl="http://test4.com" />
    </body>
</opml>

我该怎么做?我知道有Doc here,但我会很感激。

这是我到目前为止所做的:

$new = array();
foreach($podcasts as $p):
    $pod['xmlurl'] = $p['Podcast']['xmlurl'];
endforeach;
$new['opml']['body']['outline'][]=$pod;
debug($new);

$xmlObject = Xml::fromArray($new);
$xmlString = $xmlObject->asXML();
debug($xmlString);

输出debug($xmlString)

'<?xml version="1.0" encoding="UTF-8"?>
<opml>
    <body>
      <outline>
        <xmlurl>http://test1.com</xmlurl>
      </outline>
    </body>
</opml>'

1 个答案:

答案 0 :(得分:1)

好吧,您必须将其转换为链接的Cookbook文章中描述的格式,以便CakePHP可以识别它。使用@表示属性,让Xml::fromArray()返回DOMDocument个实例,以便将DOMDocument::xmlStandalone设置为true

此:

$podcasts = array(
    'podcast' => array(
        array(
            'Podcast' => array(
                'id' => '2',
                'xmlurl' => 'http://test2.com'
            )
        ),
        array(
            'Podcast' => array(
                'id' => '4',
                'xmlurl' => 'http://test4.com'
            )
        )
    )
);

$new = array (
    'opml' => array (
        '@version' => '2.0',
        'head' => null
    )
);

foreach($podcasts['podcast'] as $p) {
    $new['opml']['body']['outline'][] = array (
        '@xmlurl' => $p['Podcast']['xmlurl']
    );
};

$dom = Xml::fromArray($new, array('return' => 'domdocument'));
$dom->xmlStandalone = true;

echo $dom->saveXML();

将生成以下XML:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<opml version="2.0">
    <head></head>
    <body>
        <outline xmlurl="http://test2.com"/>
        <outline xmlurl="http://test4.com"/>
    </body>
</opml>