Writing to csv from array in php - php

I have csv files I would like to combine into a single csv file. I have managed to remove all headers. The headers write to the new file in the right column and row. But the rows from from the csv files are not lining up they start from column B instead of column A. Data from the csv is put in an array added to the new file. Is there a way I could remove the trailing commas and invoke a PHP_EOL. Here is an example of an element with data.
Array([0]=>"Joe,Soap,,,25,11,,,,,,"
[1]=>"Jimmy,Tesla,10,,4,,,,,,,,")
I would like each element to write on new line starting from column A. Here is my script.
$fileload = $filecontents;
$lines = file($fileload);
foreach ($lines as $key => $line) {
$lineArr = explode(',',$line);
if(count(array_filter($lineArray)) <= 3)
{
continue;
}
if(count(array_intersect($lineArr, $outputheaders)) >= 1)
{
continue;
}
//Row Data
$parts[] = $line;
}
$headers = implode(",",$putheaders);
$sTmp = $sTmp.$headers;
$details = implode("','",$parts);
$sTmp = $sTmp.$details;
file_put_contents($Out, $sTmp, FILE_APPEND | LOCK_EX);

Related

adding array into csv file - two array values on the same row different column

I have a php page that is creating a csv file for download which is made up of an array.
Short version of Array:
$data = array("Joe Bloggs", "jbloggs", "John Doe", "jdoe")
My array is made from output from other commands so i cant just change the layout of my array, i can make two arrays, one for names and one for usernames if that help achieve my goal.
This is what i am doing to add the array values into my csv file:
$output = fopen('php://output', 'wb');
fputcsv($output, array('Name', 'Username'));
foreach ($data as $line ) {
$val = explode(",", $line);
for ($i=0; $i<$val["count"]; $i++); {
fputcsv($output , array($val[$i]));
}
}
fclose($output);
This gives me a csv that looks like this:
Name | Username
Joe Bloggs|
jbloggs |
John Does |
jdoe |
Really i need to have the usernames on the same row but in the username column.
I have tried this and lots of variations on this but it does not seem to work, my thinking was i increase N by two each time so $i will be the name because it is every other index position and then when doing the fputcsv it would add 1 to $i so it would grab the username as it is the value after the name.
foreach ($data as $line ) {
$val = explode(",", $line);
for ($i=0; $i<$val["count"]; $i+=2); {
fputcsv($output , array($val[$i], $val[$i+1]));
}
}
fclose($output);
Using the above gives me all the values in column one still.
Apologies for the write my code style question but i am out of my depth on this and cant find how to get to two consecutive values in a for loop of an array.
Here is 1 way of doing it.
$output = fopen('php://output', 'wb');
fputcsv($output, array('Name', 'Username'));
$temp = []; //Define a temp array.
foreach ($data as $line ) {
$temp[]= $line;
if( count( $temp) == 2 ) { //If no. of values in temp array is 2, write to csv file
fputcsv($output , $temp );
$temp = []; //initialize $temp;
}
}
fclose($output);
You can use simply these two line codes.
for ($i=0 ;$i < count($data);$i+2) {
fputcsv($output , $data[$i],$data[$i+1]);
}

CSV parsing with str_getcsv fails on new line

While reading a csv file with PHP a problem occured with a line break within the CSV file. The contents of one cell will be split once a comma is followed by a line break:
$csv = array_map('str_getcsv', file($file));
first,second,"third,
more,text","forth"
next,dataset
This will result in:
1) first | second | third
2) more text | forth
3) next | dataset
While it should result in:
1) first | second | third more text | forth
2) next | dataset
Is this a bug within str_getcsv?
Don't do that, use fgetcsv(). You're having problems because file() doesn't care about the string encapsulation in your file.
$fh = fopen('file.csv', 'r');
while( $line = fgetcsv($fh) ) {
// do a thing
}
fclose($fh);
https://secure.php.net/manual/en/function.fgetcsv.php
And try not to store all the lines into an array before performing your operations if you can help it. Your system's memory usage will thank you.
<?php
$csvString = "ID,Condition,Condition,Condition,Condition,AdSize,Content:Text,Content:Text,Content:Text,Content:ImageUrl,Content:LandingPageUrl,Archive,Default
ID,Locations:Region,Device Properties:Device,Weather:Condition,Dmp:Liveramp,AdSize,title1,description1,price1,imageUrl1,landingPageUrl1,Archive,Default
ROW_001,\"Wa, Ca, Tn\",Mobile,Snow,12345,300x250,Hello Washingtonian,My Custom Description,10,http://domain/Snow.jpg,https://www.example.com,TRUE,
ROW_002,Wa,Mobile,Snow,12345,300x250,Hello Washingtonian,My Custom Description,10,http://domain/New_Snow.jpg,https://www.example.com,,
ROW_003,Wa,Mobile,,,300x250,Hello Washingtonian,My Custom Description,10,http://domain/clear.jpg,https://www.example.com,,
ROW_004,,,,,300x250,Hello,My Custom Description,20,http://domain/clear.jpg,https://www.example.com,,TRUE";
function csvToArray($csvString, $delimiter = ',', $lineBreak = "\n") {
$csvArray = [];
$rows = str_getcsv($csvString, $lineBreak); // Parses the rows. Treats the rows as a CSV with \n as a delimiter
foreach ($rows as $row) {
$csvArray[] = str_getcsv($row, $delimiter); // Parses individual rows. Now treats a row as a regular CSV with ',' as a delimiter
}
return $csvArray;
}
print_r(csvToArray($csvString));
https://gist.github.com/sul4bh/d392315c7049abd86916e077707bf123

PHP Building an array with variables

I want to build an array to create a CSV file using variables. The $arraybuild variable will gather lines from a search so will never be the same amount of rows.
$arraybuild = "'aaa,bbb,ccc,dddd',";
$arraybuild .= "'123,456,789',";
$arraybuild .= "'\"aaa\",\"bbb\"'";
$list = array
(
$arraybuild
)
;
$file = fopen("contacts.csv","w");
foreach ($list as $line)
{
fputcsv($file,explode(',',$line));
}
fclose($file);
The problem is the result does not separate the lines, it places them all in the same line.
I want to get
aaa,bbb,ccc,dddd
123,456,789
"aaa","bbb"
What I am getting is
aaa bbb ccc dddd 123 456 789 "aaa" "bbb"
All in separate columns
Can someone please assist?
Push each rows to an array instead of concatenating to a string, then loop and add to csv
$arraybuild[] = "'aaa,bbb,ccc,dddd',";
$arraybuild[] = "'123,456,789',";
$arraybuild[] = "'\"aaa\",\"bbb\"'";
$file = fopen("contacts.csv","w");
foreach ($arraybuild as $line) {
fputcsv($file, explode(',', $line));
}
fclose($file);
In your code, you are concatenating all values to one string, separated by ,. After that, you are creating one array with one element in it (that long string).
So, it's not a surprise, that you are getting all of them on the same line.
To separate lines, you should create separate arrays inside the $list array. Each included array will be on the new line.
Try this:
<?php
$arraybuild1 = "'aaa,bbb,ccc,dddd',";
$arraybuild2 = "'123,456,789',";
$arraybuild3 = "'\"aaa\",\"bbb\"'";
$list = array
(
explode(',', $arraybuild1),
explode(',', $arraybuild2),
explode(',', $arraybuild3)
);
$file = fopen("contacts.csv", "w");
foreach ($list as $fields) {
fputcsv($file, $fields);
}
fclose($file);

Create combinations of 3 arrays

I'm trying to figure out how parse a multidimensional array/loop statement to lay out the iterated array values into rows (which will become a full row in a CSV file) The CSV file will end up with 24 rows based on below example
result
1999,apple,red
1999,apple,green
1999,orange,red
1999,orange,green
1999,strawberrry,red
... and so on
$year = array('1999','2000','2001','2002');
$fruit = array('apple','orange','strawberry');
$color = array('red','green');
You can use a foreach() loop and iterate over each of the 3 arrays and use fputcsv() to save the 3 items into a CSV file.
$fp = fopen('file.csv', 'w');
$year = array('1999','2000','2001','2002');
$fruit = array('apple','orange','strawberry');
$color = array('red','green');
foreach ($year as $y) {
foreach ($fruit as $f) {
foreach($color as $c) {
echo "$y,$f,$c" . PHP_EOL; // Echo to screen. Not needed
fputcsv($fp,array($y,$f,$c)); // Save each row to CSV file
}
}
}
fclose($fp);
Resulting file.csv file will then look like so:

How can I parse a CSV with php but ignore the commas and double quotes in the strings

I am trying to parse a csv file into an array. Unfortunately one of the columns contains commas and quotes (Example below). Any suggestions how I can avoid breaking up the column in to multiple columns?
I have tried changing the deliminator in the fgetcsv function but that didn't work so I tried using str_replace to escape all the commas but that broke the script.
Example of CSV format
title,->link,->description,->id
Achillea,->http://www.example.com,->another,short example "Of the product",->346346
Seeds,->http://www.example.com,->"please see description for more info, thanks",->34643
Ageratum,->http://www.example.com,->this is, a brief description, of the product.,->213421
// Open the CSV
if (($handle = fopen($fileUrl, "r")) !==FALSE) {
// Set the parent array key to 0
$key = 0;
// While there is data available loop through unlimited times (0) using separator (,)
while (($data = fgetcsv($handle, 0, ",")) !==FALSE) {
// Count the total keys in each row
$c = count($data);
//Populate the array
for ($x = 0; $x < $c; $x++) {
$arrCSV[$key][$x] = $data[$x];
}
$key++;
} // end while
// Close the CSV file
fclose($handle);
}
Maybe you should think about using PHP's file()-function which reads you CSV-file into an array.
Depending on your delimiter you could use explode() then to split the lines into cells.
here an example:
$csv_file("test_file.csv");
foreach($csv_file as $line){
$cell = explode(",->", $line); // ==> if ",->" is your csv-delimiter!
$title[] = $cell[0];
$link[] = $cell[1];
$description = $cell[2];
$id[] = $cell[3];
}

Categories