Reputation: 493
I have a csv file which has a word for each row like this
word1
word2
word3
And have the following code to read the data:
$arr = array();
$fh = fopen('path/to/file', 'r');
while (($rows = fgetcsv($fh)) !== false) {
print_r($rows);
if (!in_array($rows[0], $arr))
$arr[] = "'".trim($rows[0])."'";
}
fclose($fh);
print_r($arr);
The problem is im getting empty strings/null for $rows[0] and im quite sure the data is there.
Array ( [0] => )
Array ( [0] => )
Array ( [0] => )
Array ( [0] => '' [1] => '' [2] => '' [3] => '' )
Any help would be greatly appreciated.
Upvotes: 1
Views: 1003
Reputation: 91734
The file reading part has already been answered, but about your loop to add the quotes, you could use array_walk()
:
function add_quotes(&$item)
{
$item = "'" . $item . "'";
}
array_walk($arr, "add_quotes");
Upvotes: 1
Reputation: 145482
Cannot reproduce. I'm assuming there is something wrong with your file format. Most likely there is an empty line on top (which I'm not quite sure, but might fail the !== false
test).
Better try:
$arr = array_map("str_getcsv", file("words.csv"));
print_r($arr);
And if you need to re-add the quotes, do a separate loop.
Upvotes: 1
Reputation: 53533
You're trying to read the words into an array? Replace all that with just:
$arr = file('/path/to/file');
print_r($arr);
Upvotes: 1