0

I've very new to PHP and trying to re-create some code I had in another language. The current version of PHP I'm working with is 7.17.

Right now, I'm trying to re-create a simple function of opening a MySQL query as a comma deliminated text file where there is no comma after the last column (just a line break). I'm trying to figure out two things right now to finish this piece of code.

  1. How do I insert the query column headers at the top of the data output (right now only the data is output, not the column headers).

  2. At the line "fwrite($output, $value.',');", I'm trying to figure out how to not add the comma after the last field (how to skip adding the comma after the last column of data).

PHP:

if (isset($_POST['download'])) {
    header('Content-Type: text/plain');
    header('Content-Disposition: attachment;filename=cars.txt');
    header('Cache-Control: no-cache, no-store, must-revalidate');
    header('Pragma: no-cache');
    header('Expires: 0');
    $output = fopen('php://output', 'w');

    while ($row = getRow($result)) {
        foreach ($row as $key => $value) {
            fwrite($output,  $value.',');
        }
        fwrite($output, "\r\n");
    }
    fclose($output);

    exit;

}

Thank You!

1 Answer 1

0

It sounds like you are trying to create a CSV file, so why not use PHP's built in CSV handling functionality (fputcsv), like so:

$output = fopen('php://output', 'w');

while ($row = getRow($result)) {
    fputcsv($output, $row);
}

fclose($output);

This way PHP does all the heavy lifting for you.

Edited based upon comment.

You could try using the answer from here to handle the encoding of the values before converting to CSV and then set the file encoding in the HTTP header to header('Content-Type: text/plain; charset=utf-8');.

Also fputcsv allows you to change the delimiter, enclosure and escape characters if they were causing you issues.

Otherwise just do:

$output = fopen('php://output', 'w');

while ($row = getRow($result)) {
    $line = implode(', ', $row);
    fwrite($output, $line);
}

fclose($output);
Sign up to request clarification or add additional context in comments.

1 Comment

The file being generated is used to directly upload into a piece of equipment where I was having problems with the formatting of CSV files and I was trying to find another working solution other than a CSV output (ANSI vs Unicode and where real line breaks are needed)..

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.