I am trying to import a csv file into a database, but I'm getting stuck on getting separately the elements of the string returned while reading the file.
I read the csv file like this:
if(!file_exists($fileURL) || !is_readable($fileURL)){
return FALSE;
}
$header = null;
$data = array();
if (($handle = fopen($fileURL, 'r')) !== FALSE)
{
while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
{
if($header === null){
$header = $row;
}
else{
$data[] = array_combine($header, $row);
}
}
fclose($handle);
}
return $data;
Then that returns an array like this:
array(1) { ["codeA codeB codeC codeD codeE codeF codeG codeH codeI codeJ codeK codeL codeM codeN codeO codeP codeQ codeR codeS codeT codeU"]=> string(293) "6928549666338 6928549666338 6928549666338 6928549666338 6928549666338 6928549666338 6928549666338 6928549666338 6928549666338 6928549666338 6928549666338 6928549666338 6928549666338 6928549666338 6928549666338 6928549666338 6928549666338 6928549666338 6928549666338 6928549666338 6928549666338" }
When I try to separate the values, it won't happen and I don't understand why!
I try to separate them like this:
$separatedArray = array();
$keys = array_keys($arrayToSeparate);
$separatedKeys = explode(" ",$keys[0]);
$values = array_values($arrayToSeparate);
$separatedValues = explode(" ",$values[0]);
foreach($separatedKeys as $i)
{
$key = $separatedKeys[$i];
$separatedArray[$key] = $separatedValues[$i];
}
return $separatedArray;
I've tried with str_getcsv, str_replace and nothing works.. I would really appreciate some help!
Change this:
$separatedKeys = explode(" ",$keys[0]);
to this:
$separatedKeys = explode(" ",preg_replace("@[\s]+@i", ' ', $keys[0]));
Do the same for the values array. Don't know why you have 2 anyways... As they both do the same.
UPDATE:
$separatedArray = explode(" ",preg_replace("@[\s]+@i", ' ', $arrayToSeparate[0]));
return $separatedArray;
UPDATE 2 (by using/changing your code):
$separatedArray = array();
$separatedValues = explode(" ", preg_replace("@[\s]+@i", ' ', $arrayToSeparate[0]));
for ($i = 0; $i < count($separatedValues); $i++) {
$separatedArray[$i] = $separatedValues[$i];
}
return $separatedArray;
try preg_match_all on \w+
i.e preg_match_all('/\w+/',$keys[0],$keys);
same for values.. your resultant array will be in keys...
Still dont understand why you are using two seperate sets, but it could be your requirement