简体   繁体   中英

getting null values while reading from csv file

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.

You're trying to read the words into an array? Replace all that with just:

$arr = file('/path/to/file');
print_r($arr);

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.

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM