Reputation: 1331
I have and XML file which is constructed like so:
<Row>
<Cell><Data>Name</Data></Cell>
<Cell><Data>Surname</Data></Cell>
<Cell><Data>Email</Data></Cell>
</Row>
<Row>
<Cell><Data>Name</Data></Cell>
<Cell><Data>Surname</Data></Cell>
<Cell><Data>Email</Data></Cell>
</Row>
<Row>
<Cell><Data>Name</Data></Cell>
<Cell><Data>Surname</Data></Cell>
<Cell><Data>Email</Data></Cell>
</Row>
<Row>
<Cell><Data>Name</Data></Cell>
<Cell><Data>Surname</Data></Cell>
<Cell><Data>Email</Data></Cell>
</Row>
What I want to do is add them to a table using PHP so far I have written this code:
<?php
$dom = new DomDocument();
$dom -> load("file.xml");
$data = $dom->getElementsByTagName('Data');
echo( "<table><tr>");
foreach( $data as $node){ echo( "<td>". $node -> textContent . "<td>");}
echo( "</tr></table>");
?>
The problem is that its appending all the data to td tags which get really long and what I need it to do is add a tr tag after the 3 data tags that are read.
Its currently creating something like:
<table>
<tr>
<td>Name</td><td>Surname</td><td>Email</td>
<td>Name</td><td>Surname</td><td>Email</td>
<td>Name</td><td>Surname</td><td>Email</td>
<td>Name</td><td>Surname</td><td>Email</td>
</tr>
</table>
I need it to be
<table>
<tr><td>Name</td><td>Surname</td><td>Email</td></tr>
<tr><td>Name</td><td>Surname</td><td>Email</td></tr>
<tr><td>Name</td><td>Surname</td><td>Email</td></tr>
<tr><td>Name</td><td>Surname</td><td>Email</td></tr>
</table>
HELP! :-)
Upvotes: 0
Views: 6302
Reputation: 11206
This involves a simple edit to your code. As you want it to appear for every third entry, you just need to move the <tr>
inside the loop.
This should solve your problem:
<?php
$dom = new DomDocument();
$dom -> load("file.xml");
$data = $dom->getElementsByTagName('Data');
$counter = 0; // Set the entry counter
echo( "<table>");
foreach($data as $node) {
if ($counter % 3 == 0) {
echo '<tr>';
}
echo "<td>". $node -> textContent . "<td>";
if($counter % 3 == 0) {
echo '</tr>';
}
$counter++; // Increment the counter
}
echo( "</table>");
?>
It's not the cleanest code, but should work.
Upvotes: 0
Reputation: 21368
Change your for
loop a bit:
$n = 0;
foreach($data as $node)
{
if($n % 3 == 0) { echo '<tr>'; }
echo( "<td>". $node -> textContent . "<td>");
if(++$n % 3 == 0) { echo '</tr>'; }
}
And remove the opening and closing tr
's that you already have in there
Upvotes: 3