使用 XMLViews 时向 rootNode 添加属性
Add attributes to rootNode when using XMLViews
我正在寻找一种在 CakePHP3 中使用 XMLViews 时为根节点添加属性的方法。该脚本生成一个简单的 sitemap.xml,它需要包含在 urlset
标记中的命名空间。没有太多代码要显示,但无论如何:
function sitemap($language='en') {
[..]
$_rootNode = 'urlset';
$this->set(compact('url'));
$this->set('_rootNode', $_rootNode);
$this->set('_serialize', ['url']);
}
我知道,我可以为 XML 添加 真实 视图,但我更喜欢这种方式
通常可以使用 @
前缀定义属性。如果是通用命名空间,您还可以使用 xmlns:
键。
为了将它们添加到根注释中,您必须将它们设置为与 url
变量处于同一级别的 view/serialization 变量,例如
$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']
另见
我正在寻找一种在 CakePHP3 中使用 XMLViews 时为根节点添加属性的方法。该脚本生成一个简单的 sitemap.xml,它需要包含在 urlset
标记中的命名空间。没有太多代码要显示,但无论如何:
function sitemap($language='en') {
[..]
$_rootNode = 'urlset';
$this->set(compact('url'));
$this->set('_rootNode', $_rootNode);
$this->set('_serialize', ['url']);
}
我知道,我可以为 XML 添加 真实 视图,但我更喜欢这种方式
通常可以使用 @
前缀定义属性。如果是通用命名空间,您还可以使用 xmlns:
键。
为了将它们添加到根注释中,您必须将它们设置为与 url
变量处于同一级别的 view/serialization 变量,例如
$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']
另见