0

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! :-)

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

PERFECT SOLUTION WORKED FIRST TIME MANY THANKS :-)
0

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.

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.