srob
srob

Reputation: 167

PHP Last in array to CSV

I have been trying to get this code to work for ages now and have looked at other questions but it is not working for me. Any guidance is greatly appreciated.

In context, there is a sql query to bring back all of the results for today's entries. These are converted to a CSV file every day. To import into the software then the end of each row must return "" and a carriage return except the last row which should not add a carriage return.

The code is below:

    $xo1 = "\"\"";
    $xo2 = "\r\n";

    while ($row = mysql_fetch_array($sql)) {
    for ($i = 0; $i < $columns_total; $i++) {
    $output .='"'.$row["$i"].'",';

    if(++$i === $columns_total){
    $xo1 = "";
    $xo2 = "";}
    }
    $output .= $xo1;
    $output .= $xo2;
    }

Upvotes: 0

Views: 48

Answers (2)

Pakspul
Pakspul

Reputation: 648

You can also use the index of the loop for this problem. When index is above zero apply the $xo1 and $xo2. For example:

for ($i = 0; $i < $columns_total; $i++) {
    if ( $i > 0 ) {
        $output .= $xo1 . $xo2;
    }

    // now apply other workings
    $output .='"'.$row["$i"].'",';
}

Upvotes: 1

Lars Beck
Lars Beck

Reputation: 3584

I guess rtrim() should do the job, if I got the question right.

while ( $row = mysql_fetch_array( $sql ) ) {
    foreach( $row as $column ) {
        $output .= sprintf( '"%s",""' . "\r\n" , $column );
    }
}
rtrim( $output, '""' . "\r\n" );

Upvotes: 1

Related Questions