Reputation: 573
I have the following in a CSV file exported from Excel
Lol,Man,11
Hello,World,11
My,Name,12
Is,Epic,11
How would I parse this using PHP to an array?
Currently I am using
$line = file_get_contents("Day1.CSV");
$parsed = str_getcsv(
$line, # Input line
',', # Delimiter
'"', # Enclosure
'//' # Escape char
);
But that's not working.
Upvotes: 0
Views: 5392
Reputation: 11485
You can use fgetcsv (example from the manual page)
if (($handle = fopen("Day1.CSV", "r")) !== FALSE)
{
while (($data = fgetcsv($handle, 1000, ",", "//")) !== FALSE)
{
// do something with the data here
echo $data[0] . " - ". $data[1] . " - ". $data[2] . "</br>" ;
}
fclose($handle);
}
Alternatively in your implementation, you can do this:
$contents = file_get_contents("Day1.CSV");
$data = str_getcsv("\n");
foreach ($data as $row)
{
$output = str_getcsv($row, ',', '"', '//');
// do something with the data here
echo $output[0] . " - " $output[1] . " - " $output[2] . "\n";
}
HTH
Upvotes: 2
Reputation:
<?php
$str="Lol,Man,11";
$out=str_getcsv($str,",",'','');
print_r($out); //Array ( [0] => Lol [1] => Man [2] => 11 )
OR
$out=explode(",",$str);
Upvotes: 0