0

I'd like to transform this given array

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'
            )
        )
    )
)

into this String with 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>

How would I do this? I know there is a Doc here, but I would appreciate help nevertheless.

This is what I have so far:

$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);

Output debug($xmlString):

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

1 Answer 1

1

Well, you have to transform it into a format as described in the linked Cookbook article, so that CakePHP can recognize it. Use @ to indicate attributes, and let Xml::fromArray() return an DOMDocument instance so that you can set DOMDocument::xmlStandalone to true.

This:

$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();

will generate the following 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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.