0

I got a string with semi clones. I want to create a csv file.

$fp = fopen("abc.csv", "w");
$str = "FRUIT; STOCKS; TYPE\n lychee; B-type,A-type; instocks\n strawberry; A-type;N/A\n";

$rows = str_getcsv($str, PHP_EOL);
foreach($rows as $row) {
    $data = str_getcsv($row);
    fputcsv($fp, explode(';',$data), ";");
}

The fputcsv() doesn't seem to work correctly.

When I open the csv using EXCEL the data should be in separate columns where the semi colon (;) was.

FRUIT       TYPE           STOCKS
Lychee      B-type,A-type  instocks
Strawberry  A-type         N/A

EDIT:

My current output and problems are 1. If there's are more than one words those are wrapped by a " (e.g. below)

FRUIT;STOCKS;TYPE;"COST PER ITEM"
  1. The final output is as (when opened in excel).

    FRUIT;STOCKS;TYPE;"COST PER ITEM" Lychee "B-type A-type"; instocks; $54; Strawberry; A-type; N/A; $31;

Each ; is in a seperate column. I want the final output to be like this

FRUIT       TYPE           STOCKS    COST PER ITEM
Lychee      B-type,A-type  instocks  $54
Strawberry  A-type         N/A       $31
4
  • fputcsv() works perfectly well, what is your actual problem? What result are you getting? Commented Apr 6, 2016 at 9:16
  • 1
    If there is more than one word in a column, then it should be wrapped in quotes..... that's what the CSV specification says should happen.... this is not_ a problem Commented Apr 6, 2016 at 9:34
  • See the edit to my answer Commented Apr 6, 2016 at 9:39
  • Try to open the csv file in any editor not excel & post the content. Commented Apr 6, 2016 at 9:42

1 Answer 1

1

Don't try to use str_getcsv() to parse the whole string into lines, str_getcsv() is designed to parse a single row, not the entire content of a file/string

$str = "FRUIT; STOCKS; TYPE\n lychee; B-type,A-type; instocks\n strawberry; A-type;N/A\n";

$rows = explode("\n", $str);

foreach($rows as $row) {
    $data = str_getcsv($row, ';');
    $data = array_map('trim', $data);
    fputcsv($fp, $data, ';');
}

EDIT

It looks as though your MS Excel may be expecting a comma (,) as separator rather than a semi-colon (;).... so you may need to tell MS Excel this

explicitly write a sep=; line as the first line of your file

fwrite($fp, 'sep=;'.PHP_EOL);

before your data loop

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

1 Comment

Thank you. I tried your suggestion. Output was same as in my original code. Please see my edit.

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.