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);
Related
It is about this situation:
I have a lot of txt files and one 1 line, there are tags stored, some alone, some comma seperated.
So an txt file looks like this:
...
aaa,bbb,ccc // tag line; 3 tags
...
or
...
aaa,ccc // tag line; 2 tags
...
or
...
bbb // tag line;single tag
...
What i want to achieve: read all the tag lines in each txt file and put the tags in an array. Tags with the same name should occure only once in the array (array_unique)
What i have so far:
$files = glob("data/articles/*.txt");
$tag_lines = array();
$lines = file($file, FILE_IGNORE_NEW_LINES);
$tag_lines[] = $lines[7]; // 7th line is the tag line. Put all the tags in an array
foreach($tag_lines as $tag_line) {
echo $tag_line;
}
Assuming when there is only 1 tag in each line, this works fine.
Lets say i have 3 txt files.
When some lines have multiple tags, comma seperated, my output looks like this:
aaa,bbb,ccc
aaa,ccc
bbb
and the output should be like this :
aaa
bbb
ccc
I tried this:
foreach($files as $file) { // Loop the files in the directory
$lines = file($file, FILE_IGNORE_NEW_LINES);
$single_tag_line = explode(',' , $lines[7]);
$tag_lines[] = $lines[7];
$tag_lines = array_unique(array_merge($tag_lines , $single_tag_line));
}
foreach($tag_lines as $tag_line) {
echo $tag_line;
}
Unfortunately, i still got an output like this:
aaa,bbb,ccc
aaa,ccc
bbb
For each file: read it, retrieve the 7th line, split that line on commas, and for each string in that line, add it to an array of unique keys, using the string as the array key.
$unique_tags = [];
foreach ( glob("data/articles/*.txt") as $file ) {
$lines = file($file, FILE_IGNORE_NEW_LINES);
$tags = explode( ',', $lines[7] ); // 7th line is the tag line. Put all the tags in an array
// Process each tag:
foreach ( $tags as $key ) {
$unique_tags[ $key ] = $key;
}
}
At that point, $unique_tags will contain all the unique keys (as both keys and values).
Another option, based on the answer above is to use array_count_values. In that case, you have all the keys of the array unique, but it calculates also the number of keys that occurs in the array:
$files = glob("data/articles/*.txt");
foreach($files as $file) { // Loop the files in the directory
$lines = file($file, FILE_IGNORE_NEW_LINES);
$tags = explode( ',', strtolower($lines[7]) ); // 7th line is the tag line. Put all the tags in an array
// Process each tag:
foreach ($tags as $key) {
$all_tags[] = $key; // array with all tags
//$unique_tags[$key] = $key; // array with unique tags
}
}
$count_tags = array_count_values($all_tags);
foreach($count_tags as $key => $val) {
echo $key.'('.$val.')<br />';
}
Your output will be something like:
aaa(2) // 2 keys found with aaa
bbb(2) // 2 keys found with bbb
ccc(2) // 2 keys found with ccc
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]);
}
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:
I am trying to import a CSV for a shop, with a subset of data from an existing CSV file. I need to split one item from a column (column 3, category_id) that contains multiple comma-separated values, then combine it with one other column (Product_id) to produce multiple rows in the import CSV. See the following examples.
Original CSV
Product_id;article_id;category_id;
"1";"0001";"2,4,6"
Need it into a new CSV file
Product_id;category_id
"1";"2"
"1","4"
"1","6"
I tried just the fegetcsv function to read in the CSV and to printout the whole into an array but I have no idea what to do next.
<?php
$handle = fopen ("articles.csv","r");
while ( ($data = fgetcsv ($handle, 1000, ";")) !== FALSE ) {
$column3[] = $data[3];
}
fclose ($handle);
//edit:
print_r($column3);
?>
I get:
Array ([0] => category_id [1] => 1 [2] => 0001 [3] => 2,4,6
Quick and dirty:
$csvData = file('articles.csv');
$matches = array();
$output = "";
foreach($csvData as $csvLine) {
if(preg_match('/"(.+)";".+";"(.+)"/', $csvLine, $matches))
{
$numbers = explode(',', $matches[2]);
foreach($numbers as $number) {
$output .= "\"{$matches[1]}\";\"{$number}\"" . PHP_EOL;
}
}
}
I've a problem to import a single cell in csv,
i have a csv file that contain 7 column and ~1420 row,
i need to read only the 4 column number in 1420's row, how can i do it?
<?php
$url = "wp-admin/ftp/test.csv";
$csvData = file_get_contents($url);
$lines = explode("\n", $csvData);
$array = array();
foreach ($lines as $line) {
$array[] = str_getcsv($line);
}
echo $array[1];
?>
with this i have an array to output with all cell in one row,
but i need to take the third number in that row, and not all of it.
I believe $array is multidimensional the following should print what you want:
echo $array[1419][3];
Otherwise you can print it to check how it is structured:
print_r($array);
UPDATE: unidimensional
foreach ($lines as $line) {
$array[] = str_getcsv($line)[3];//PHP 5.4
}
echo $array[1419];