phpxmlcakephpcakephp-3.0xml-attribute

Add attributes to rootNode when using XMLViews


I am looking for a way to add attributes for the root node when using XMLViews in CakePHP3. The Script generates a simple sitemap.xml which needs the namespace included in the urlset tag. Not to much code to show, but anyway:

function sitemap($language='en') {
    [..]
    $_rootNode = 'urlset';
    $this->set(compact('url'));
    $this->set('_rootNode', $_rootNode);
    $this->set('_serialize', ['url']);
}

I am aware, that I could add real views for the XML, but I would prefer this way of doing this


Solution

  • Generally attributes can be defined using the @ prefix. In case of a generic namespace you could also use the xmlns: key.

    In order to add them to the root note, you have to set them as view/serialization variables at the same level as the url variable, ie something like

    $attributes = [
        'xmlns:' => 'http://www.sitemaps.org/schemas/sitemap/0.9', // or
        // '@xmlns' => 'http://www.sitemaps.org/schemas/sitemap/0.9',
        // ...
    ];
    $this->set($attributes + compact('url'));
    $this->set('_rootNode', $_rootNode);
    $this->set('_serialize', array_merge(array_keys($attributes), ['url']));
    

    So that you end up with a dataset that looks like

    [
        'xmlns:' => 'http://www.sitemaps.org/schemas/sitemap/0.9',
        // ...
        'url' => [
            // ...
        ]
    ]
    

    and a serialization set like

    ['xmlns:' /*, ... */, 'url']
    

    See also