Place a while loop in a string

时间:2015-09-01 22:29:07

标签: php

I would like to create a function where users can create there own XML feed. The feed should be for example the following (quite simple example) feed:

<xml>
  <products>
    <product>Product 1</product>
    <product>Product 2</product>
  </products>
</xml>

Very important in the setup is that there is a connection between the database and the setup feed, for example the is loaded from the database. So, the user should create for example the following 'text/xml' as basis:

<xml>
  <products>
    %whileProducts%
      <product>%title%</product>
    %/whileProducts%
  </products>
</xml>

It is possible to enter the product title via a str_replace, but is it also possible to create a while loop via a replace function? To make it a bit more difficult: it could be possible that there are multiple loops in a loop, for example, a user would like to create a feed with a while loop for the products and inside this loop a new loop for the colors and/or sizes of the product.

1 个答案:

答案 0 :(得分:2)

No, it's not. str_replace() can only perform literal replacements of one set of constant strings with another corresponding set of constant strings; it can't do anything more complex.

What you want here is a templating engine. Since XML is involved, XSLT may be an appropriate tool to use; it's not simple, though. There are many other templating engines for PHP available, and recommending one is outside the scope of this question.