0

我想转换这个给定的数组

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,但我还是很感激帮助。

这是我到目前为止所拥有的:

$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>'
4

1 回答 1

1

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

这个:

$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>
于 2013-06-23T16:44:24.327 回答