gieldops
gieldops

Reputation: 385

PHP include file multiple times in one page

I have a php-file called kal_test.php which gives a value to the variable $vbl. This variable is needed in the file called kal_generator.php which produces a table from that variable (I'll spare you the details). It goes like this:


[kal_test.php]

<?php
$vbl = "14/09/2011";
include ("kal_generator.php");
?>

[kal_test.php]

<?php
// Long code converts the $vbl into a 2-dimensional array called $output
// I'll spare you the details (it works fine by the way)
?>

<table>
  <tr><th>bla</th><th>blabla</th></tr>

<?php
foreach ($output as $v1) {
    echo "<tr>";
    foreach ($v1 as $v2) {
        echo "<td>$v2</td>";
    }
    echo "</tr>\n";
}
?>

</table>

This set-up works fine but I can't make two of those appear on the same page, like this:

[kal_test.php]

<?php
$vbl = "14/09/2011";
include ("kal_generator.php");
$vbl = "21/09/2011";
include ("kal_generator.php");
?>

This will give the following result:

//here comes the header

<table> // table created with $vbl = "14/09/2011"
  <tr><th>bla</th><th>blabla</th></tr>
  <tr><td>this</td><td>works</td></tr>
  <tr><td>this</td><td>works</td></tr>
</table>

//here should the second table be and also the rest of the page (footer), this is completely missing

What am I doing wrong? Thanks!

Upvotes: 6

Views: 19654

Answers (1)

Lekensteyn
Lekensteyn

Reputation: 66415

You're likely defining a function or class in kal_generator.php. PHP aborts when you try to redefine such a function or class. Consider putting your code in a function, include that function once and then run the function instead of including a file.

kal_test.php

<?php
require_once 'kal_generator.php';
kal_generator("14/09/2011");
kal_generator("21/09/2011");
?>

kal_generator.php

<?php
function kal_generator($vbl) {
    /**
     * Here, you should be creating $output
     */
    echo <<EOF
<table>
  <tr><th>bla</th><th>blabla</th></tr>

EOF;
    foreach ($output as $v1) {
        echo "<tr>";
        foreach ($v1 as $v2) {
            echo "<td>$v2</td>";
        }
        echo "</tr>\n";
    }

    echo "</table>\n";
}
?>

Upvotes: 15

Related Questions