-1

Hello I have an array in PHP that looks like the following :

Array
(
    [0] => 20140723,8,156.62,LTD.
20140418-23,16-4010061201,936-438-2501,Y,23,20140418,V849,10.00
20140418-29,16-4010091102,936-438-2501,Y,29,20140418,V849,2.00
0,16-4010091102,936-436-0524,works.com,Y,0,20140723,0,0
0,16-4010061201,936-438-2501,waterw.com,Y,0,20140723,0,0
0,16-4010091102,936-438-2501,waterworks.com,Y,0,20140723,0,0
    [1] => 140723-1548.csv
)

What I would like to do is to create a csv file that has as content the first index of the array above and as title the second array index. I used the following function :

function createCSV($Myarray, $filename){
    $fp = fopen($filename, "w");
    fputcsv($fp, array($Myarray)); 
    fclose($fp);  
}

and I called it like that :

createCSV($Myarray[0], $Myarray[1]);//$Myarray is the array above

the problem I have is that the first cell in the csv output has all the data from the first index of the array, what I would like is to have each first index array line in a row in the csv.

Thanks

5
  • Why don't you put each cell in its own index of the array? That would make more sense. Commented Jul 23, 2014 at 22:59
  • 0 is that one row in the csv? multiple rows? how are they delimited ? Commented Jul 23, 2014 at 23:01
  • can explain more what you mean please? Commented Jul 23, 2014 at 23:01
  • this is supposed to be the first row in the csv output : 20140418-23,16-4010061201,936-438-2501,Y,23,20140418,V849,10.00 my issue is that I have this entire line in one cell Commented Jul 23, 2014 at 23:02
  • are there real line breaks in the string? how do you know when a row ends? Commented Jul 23, 2014 at 23:04

1 Answer 1

0

use the following code

 function createCSV($Myarray, $filename){
    $fp = fopen($filename, "w");
    fputcsv($fp, split(',',$Myarray)); 
    fclose($fp);  
 }

or simply

function createCSV($Myarray, $filename){
    $fp = fopen($filename, "w");
    fputs($fp, $Myarray); 
    fclose($fp);  
 }

explaination:

fputcsv creates one cell in the csv for corresponding array elements irrespective of the data in he array. in your case you are just passing one array element with comma seperated string as value. fputcsv is behaving correctly to make only a single csv column. so either user fput or split the data in multiple array elements

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

1 Comment

Hi, thanks it is working as i want , you should change fput to fputs because there is no fput in PHP

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.