0

I want to insert a for loop inside a foreach loop in xml file but I cant do that

catalog.xml:

<?xml version="1.0" encoding="UTF-8"?>
<movies>
  <cd>
    <title>Avatar</title>
  </cd>
  <cd>
    <title>Captain America</title>
  </cd>
  <cd>
    <title>Ironman</title>
  </cd>
</movies>

xsl:

<?php
  $loop = 2;
?>
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
  <html>
  <body>
    <table border="1">
      <xsl:for-each select="movies/cd">
      <tr>
        <td><xsl:value-of select="title"/></td>
      </tr>
      </xsl:for-each>
    </table>
  </body>
  </html>
</xsl:template>
</xsl:stylesheet>

Result: Avatar Captain America Ironman

Let say I only want the foreach loop to run certain time only by the count of the variable $loop(if $loop=2 the it will run 2 times only)?

Expected Result:

$loop =2;

**Avatar
Captain America**
0

1 Answer 1

1

The xsl:for-each instruction is not a "loop". Each node in the selected node-set is processed independently, and there is no exit condition.

If you want to limit the processing to the first 2 cds only, you can do simply:

XSLT 1.0

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/movies">
    <html>
        <body>
            <table border="1">
                <xsl:for-each select="cd[position() &lt;= 2]">
                    <tr>
                        <td>
                            <xsl:value-of select="title"/>
                        </td>
                    </tr>
                </xsl:for-each>
            </table>
        </body>
    </html>
</xsl:template>

</xsl:stylesheet>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.