user3572565
user3572565

Reputation: 751

Create csv file after looping through array in php

I have looped through an array and can successfully print out the rows that I need to work with

foreach($array['Stock'] as $row) {
    echo '|' . $row['Code'] . '|' . intval($row['Onhand']) . "\r\n";
}

I need to have all of the printed rows to be saved in a csv file. Should I be converting to an array first and then creating a csv or can I do it from within the loop?

Just to clarify guys, the file requirements are

'This CSV file must contain 3 columns, separated by the pipe symbol (|), without column names. '

Upvotes: 1

Views: 858

Answers (1)

Jamie Bicknell
Jamie Bicknell

Reputation: 2326

Prepend each row onto a variable like:

$csv .= $row['Code'] . ',' . intval($row['Onhand']) . "\r\n";

Then use file_put_contents to save to local file, or use header to output headers to force download to browser.

PS: CSV stands for comma separated values, not pipe separated values, so if I'm correct in assuming you're using the pipe | to separate values it's best to use a comma instead.

Upvotes: 3

Related Questions