This question already has answers here:
Convert flat array to a delimited string to be saved in the database
(13 answers)
Closed 5 years ago.
I import a CSV file with the following code (extract):
while(($line = fgetcsv($csvFile, 0, "\t")) !== FALSE){
//some mysql insert
$aff[] = $line[12];
}
Now I need to get some items to use them later in the code. I added the $aff variable, but was not able to create a string from the items.
The final string should be seperated with a comma: a, b, c
How can I do that? If I print the $aff out, it only says "Array".
Use php's implode function -
http://php.net/manual/en/function.implode.php
$string = implode(",", $aff);
That will create a string separated by commas from your array.
This is a very basic PHP question. Googling something like concatenate array or something should give you the answer right away. The correct approach would be to use the function implode with a separator:
echo implode(', ', $aff);
Also note that you should create the array outside of your loop if you don't already do this:
// Create empty array
$aff = [];
while(($line = fgetcsv($csvFile, 0, "\t")) !== FALSE){
//some mysql insert
$aff[] = $line[12];
}
// Output the array
echo implode(', ', $aff);
Try this, use concatenating assignment operato and do rtrim and you got your solution
$str = "";
while(($line = fgetcsv($csvFile, 0, "\t")) !== FALSE){
//some mysql insert
$str .= $line[12].", ";
}
echo echo rtrim($str,", ");
Related
This question already has answers here:
Print array to a file
(14 answers)
How do I store an array in a file to access as an array later with PHP?
(8 answers)
Closed 8 months ago.
I am trying to write an array to a file in php. If I do
$var = "Var";
fwrite($file, "<?php \$var = '$var';");
and I echo $var in the new file it will return "Var". But if I do the same thing with an array it will return "Array". How can I fix this?
The var_export() function does exactly what you want: it outputs a variable in a way it can be used in a .php file. Please note that when using var_export, you should drop the quotes around your variable in the output string.
fwrite($file, "<?php \$var = ".var_export($var, true).";");
You need to turn the array into a string that is separated by a comma. This is one of those problems where you will run into lots of edge cases. For instance, the below code will fail if one of the elements in the array contains a ' single quote character.
<?php
$hello = 'Hello';
$world = 'World';
$integer = 100;
$array = [
$hello,
$world,
$integer
];
function add_quotes($e) {
if (is_string($e))
return sprintf("'%s'", $e);
else
return $e;
}
$php_string = '<?php
$array = [';
$php_string .= implode(',', array_map('add_quotes', $array));
$php_string .= '];';
$fp = fopen('output.php', 'w');
fwrite($fp, $php_string);
This will output
<?php
$array = ['Hello','World',100];
How you fix things depends very much on what you want to do with the stored data.
The simple example is to write each element separately:
<?php
$arr = ['Apple','Orange','Lemon'];
$fh = fopen('myFile.csv', 'w');
foreach($arr as $el) {
fwrite ($fh, "$el\n"); // add a new line after each element to delimit them
}
fclose($fh);
You could create a CSV file with fputcsv():
<?php
$arr = ['Apple','Orange','Lemon'];
$fh = fopen('myFile.csv', 'w');
fputcsv($fh, $arr);
fclose($fh);
You could write JSON data:
<?php
$arr = ['Apple','Orange','Lemon'];
file_put_contents('myFile.json', json_encode($arr));
If you're feeling bold you could create an XML file (no snippet for this one, but trust me, it can be done).
You could write serialized PHP data (see serialize()) - not recommended.
Or you could create your own format for your specific application.
This question already has answers here:
Remove Blank ROWS from CSV files in php
(5 answers)
Closed 9 years ago.
In my code I'm reading csv file with fgetcsv function
while($line = fgetcsv($handle, 4096)){
.....
}
How can check when the $line is empty, I mean $line = ',,,,,,,,' ?
note: I'm not always know the number of columns.
One way to do it would be:
if (str_replace(array(',', ' '), '', $line) != '') {
// do something
}
Basically, it will compare the line after you remove all comma's and spaces from the string.
You can take the contents of file in an array and check which index has empty value.
like this -
$handle = fopen("file.csv","r");
$data = fgetcsv($handle,",");
while($data = fgetcsv($handle))
{
$array = explode(",",$data[0]);
print_r($array);
}
fclose($handle);
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];
}
I have made a simple form with textfields, when i submit a button it wrties all textfield values into a .txt file. Here is an example of the .txt file content:
-----------------------------
How much is 1+1
3
4
5
1
-----------------------------
The 1st and last line ---- is there to just seperate data. The 1st line after the ---- is the question , the before the bottom seperator (1) is the true answer, and all the values between question and true answer are false answers.
What i want to do now is echo out the question , false answers and true answer , seperatly:
echo $quesiton;
print_r ($false_answers); //because it will be an array
echo $true answer;
I think the solution is strpos , but i dont know how to use it the way i want it to. Can i do somethinglike this? :
Select 1st line (question) after the 1st seperator
Select 1st line (true answer) before the 2nd seperator
Select all values inbetween question and true answer
Note that im only showing one example, the .txt file has a lot of these questions seperated with -------.
Are my thoughs correct about using strpos to solve this? Any suggestions?
Edit:
Found some function:
$lines = file_get_contents('quiz.txt');
$start = "-----------------------------";
$end = "-----------------------------";
$pattern = sprintf('/%s(.+?)%s/ims',preg_quote($start, '/'), preg_quote($end, '/'));
if (preg_match($pattern, $lines, $matches)) {
list(, $match) = $matches;
echo $match;
}
I think this might work, not sure yet.
You may try this:
$file = fopen("test.txt","r");
$response = array();
while(! feof($file)) {
$response[] = fgets($file);
}
fclose($file);
This way you will get response array like:
Array(
[0]=>'--------------',
[1]=>'How much is 1+1',
[2]=>'3',
[3]=>'4',
[4]=>'2',
[5]=>'1',
[6]=>'--------------'
)
You could try something like this:
$lines = file_get_contents('quiz.txt');
$newline = "\n"; //May need to be "\r\n".
$delimiter = "-----------------------------". $newline;
$question_blocks = explode($delimiter, $lines);
$questions = array();
foreach ($question_blocks as $qb) {
$items = explode ($newline, $qb);
$q['question'] = array_shift($items); //First item is the question
$q['true_answer'] = array_pop($items); //Last item is the true answer
$q['false_answers'] = $items; //Rest of items are false answers.
$questions[] = $q;
}
print_r($questions);
I'm trying to read data from a.csv file to ouput it on a webpage as text.
It's the first time I'm doing this and I've run into a nasty little problem.
My .csv file(which gets openened by Excel by default), has multiple rows and I read the entire thing as one long string.
like this:
$contents = file_get_contents("files/data.csv");
In this example file I made, there are 2 lines.
Paul Blueberryroad
85 us Flashlight,Bag November 20,
2008, 4:39 pm
Hellen Blueberryroad
85 us lens13mm,Flashlight,Bag,ExtraBatteries November
20, 2008, 16:41:32
But the string read by PHP is this:
Paul;Blueberryroad 85;us;Flashlight,Bag;November 20, 2008, 4:39 pmHellen;Blueberryroad 85;us;lens13mm,Flashlight,Bag,ExtraBatteries;November 20, 2008, 16:41:32
I'm splitting this with:
list($name[], $street[], $country[], $accessories[], $orderdate[]) = split(";",$contents);
What I want is for $name[] to contain "Paul" and "Hellen" as its contents. And the other arrays to receive the values of their respective columns.
Instead I get only Paul and the content of $orderdate[] is
November 20, 2008, 4:39 pmHellen
So all the rows are concatenated. Can someone show me how i can achieve what I need?
EDIT: solution found, just one werid thing remaining:
I've solved it now by using this piece of code:
$fo = fopen("files/users.csv", "rb+");
while(!feof($fo)) {
$contents[] = fgetcsv($fo,0,';');
}
fclose($fo);
For some reason, allthough my CSV file only has 2 rows, it returns 2 arrays and 1 boolean. The first 2 are my data arrays and the boolean is 0.
You are better off using fgetcsv() which is aware of CSV file structure and has designated options for handling CSV files. Alternatively, you can use str_getcsv() on the contents of the file instead.
The file() function reads a file in an array, every line is an entry of the array.
So you can do something like:
$rows = array();
$name = array();
$street = array();
$country = array();
$rows = file("file.csv");
foreach($rows as $r) {
$data = explode(";", $r);
$name[] = $data[0];
$street[] = $data[1];
$country[] = $data[2];
}
I've solved it now by using this piece of code:
$fo = fopen("files/users.csv", "rb+");
while(!feof($fo)) {
$contents[] = fgetcsv($fo,0,';');
}
fclose($fo);
For some reason, allthough my CSV file only has 2 rows, it returns 2 arrays and 1 boolean. The first 2 are my data arrays and the boolean is 0.
The remark about fgetcsv is correct.
I will still answer your question, for educational purpose. First thing, I don't understand the difference between your data (with comas) and the "string read by PHP" (it substitutes some spaces with semi-colon, but not all?).
PS.: I looked at the source code of your message, it looks like an odd mix of TSV (tabs) and CSV (coma).
Beside, if you want to go this way, you need to split first the file in lines, then the lines in fields.
The best way is of course fgetcsv() as pointed out.
$f = fopen ('test.csv', 'r');
while (false !== $data = fgetcsv($f, 0, ';'))
$arr[] = $data;
fclose($f);
But if you have the contents in a variable and want to split it, and str_getcsv is unavailable you can use this:
function str_split_csv($text, $seperator = ';') {
$regex = '#' . preg_quote($seperator) . '|\v#';
preg_match('|^.*$|m', $text, $firstline);
$chunks = substr_count($firstline[0], $seperator) + 1;
$split = array_chunk(preg_split($regex, $text), $chunks);
$c = count($split) - 1;
if (isset($split[$c]) && ((count($split[$c]) < $chunks) || (($chunks == 1) && ($split[$c][0] == ''))))
unset($split[$c]);
return $split;
}