我正在寻找一种在 CakePHP3 中使用 XMLViews 时为根节点添加属性的方法。该脚本生成一个简单的 sitemap.xml,它需要包含在
urlset
标签中的命名空间。没有太多代码要显示,但无论如何:
function sitemap($language='en') {
[..]
$_rootNode = 'urlset';
$this->set(compact('url'));
$this->set('_rootNode', $_rootNode);
$this->set('_serialize', ['url']);
}
我知道,我可以为 XML 添加 real 视图,但我更喜欢这种方式
通常可以使用
@
前缀来定义属性。如果是通用命名空间,您还可以使用 xmlns:
键。
为了将它们添加到根注释中,您必须将它们设置为与
url
变量处于同一级别的视图/序列化变量,即类似
$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']));
这样你最终会得到一个看起来像这样的数据集
[
'xmlns:' => 'http://www.sitemaps.org/schemas/sitemap/0.9',
// ...
'url' => [
// ...
]
]
和一个序列化集,如
['xmlns:' /*, ... */, 'url']
另请参阅