迭代数组并替换模板中的数据
我有一个带有“标签”的 XML 文档,这些“标签”根据数组中的数据进行替换。标签有两种类型,一种是定义集合的父标签,另一种是简单地用值替换的标签。以下是用于构建和填充模板的数据示例:
$array = array(
'name' => 'name',
'city' => 'city',
'addresses' => array(
array(
'street' => '123',
'city' => 'main'
),
array(
'street' => '123',
'city' => 'main'
'phone' => array(
array(
'home' => '123456', 'work' => '1234567'
)
以下是示例模板:
<name>%name%</name>
<city>%city%</city>
%%addresses%%
<street>%street%</street>
<city>%city%</city>
%%phone%%
<home>%%home%%</home>
<work>%%work%%</work>
%%/phone%%
%%/addresses%%
数组的键值与模板内的标签相匹配。如果键本身是一个数组,那么它将循环该键的标记 (%%) 中包含的数据。
我尝试过执行递归函数,但它似乎只能深入一层。
有人有什么建议吗?谢谢你!
I have an XML document with "tags" that are replaced based on data within an array. There are two types of tags, one is a parent tag to define a set, another is simply a tag that is replaced by a value. Here's an example of the data used to build and fill in the template:
$array = array(
'name' => 'name',
'city' => 'city',
'addresses' => array(
array(
'street' => '123',
'city' => 'main'
),
array(
'street' => '123',
'city' => 'main'
'phone' => array(
array(
'home' => '123456', 'work' => '1234567'
)
Here is an example template:
<name>%name%</name>
<city>%city%</city>
%%addresses%%
<street>%street%</street>
<city>%city%</city>
%%phone%%
<home>%%home%%</home>
<work>%%work%%</work>
%%/phone%%
%%/addresses%%
The key values of the array, match the tags within the template. If the key is an array itself, then it loops through the data contained within that key's tag (%%).
I've tried doing a recursive function but it only seems to work one level deep.
Does anyone have any suggestions? Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我建议您使用“正常工作”的现有简单模板语言tm,例如 Mustache(还有很多其他的)。我知道 Mustache 支持数组循环,使用它,完成工作,易于集成。适用于多种语言。
I suggest you use an existing simple template language that "just works"tm, like Mustache (there are plenty much others). I know that Mustache supports looping over arrays, used it, does the job, easy to integrate. Available for many languages.