2

I am exporting data to CSV and facing one problem.

$data['name'] = "Test";
$data['category'] = "category1, category2, caegory3";

When I export code to CSV, it exports records but make separate column for category1, separate column for category 2 and separate column for category3.

Current Output
-------------------------------------------
| Name | Category  |           |           |
-------------------------------------------- 
| TEst | category1 | category2 | category3 |
--------------------------------------------


 Expected Output

------------------------------------------------------------
| Name | Category                      |         |         |
-------------------------------------------- ---------------
| TEst | category1,category2,category3 |         |         |
------------------------------------------------------------

What should I do so comma-separated String fall in same column?

2 Answers 2

6

You should have category values between "" so the comma is not interpreted. You can change code like this:

$data['name'] = 'Test';
$data['category'] = '"category1, category2, caegory3"';
Sign up to request clarification or add additional context in comments.

Comments

1

You should really take a look at fputcsv. It does exactly what you want, with different escaping characters and so on.

http://php.net/manual/en/function.fputcsv.php

If you wish to output it to the buffer instead of a file you can use $fh = fopen('php://output', 'w'); to write to the client.

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.