Skip to content

Instantly share code, notes, and snippets.

@wescleymatos
Created May 8, 2012 19:05
Show Gist options
  • Save wescleymatos/2638542 to your computer and use it in GitHub Desktop.
Save wescleymatos/2638542 to your computer and use it in GitHub Desktop.
Conversão array->csv csv->array
<?php
/**
* Zend Framework
*
* LICENSE
*
* Arquivo de livre reprodução
*
* Utilização:
*
* echo '<pre>';
* print_r(CsvToArray('teste.csv'));
* echo '</pre>';
*
*
*
* @category CSV
* @package ScvToArray
* @copyright Copyleft (c) 2009-2010 . (http://www.pontophp.com.br)
* @version 1.0
*/
final class csvtoarray{
/**
* Função estática principal. O parâmetro $delimiter não é obrigatório, apenas se for utilizado outro tipo de caractere, por exemplo a vírgula (,).
*
* @param string $file
* @param char $delimiter
* @return array
*/
public static function open($file, $delimiter = ';'){
return self::ordenaMultiArray(self::csvArray($file, $delimiter), 0);
}
private function csvArray($file, $delimiter)
{
$result = Array();
$size = filesize($file) + 1;
$file = fopen($file, 'r');
$keys = fgetcsv($file, $size, $delimiter);
while ($row = fgetcsv($file, $size, $delimiter))
{
for($i = 0; $i < count($row); $i++)
{
if(array_key_exists($i, $keys))
{
$row[$keys[$i]] = $row[$i];
}
}
$result[] = $row;
}
fclose($file);
return $result;
}
function ordenaMultiArray($multiArray, $secondIndex)
{
while (list($firstIndex, ) = each($multiArray))
$indexMap[$firstIndex] = $multiArray[$firstIndex][$secondIndex];
asort($indexMap);
while (list($firstIndex, ) = each($indexMap))
if (is_numeric($firstIndex))
$sortedArray[] = $multiArray[$firstIndex];
else $sortedArray[$firstIndex] = $multiArray[$firstIndex];
return $sortedArray;
}
/**
* Generatting CSV formatted string from an array.
* By Sergey Gurevich.
*/
private function array_to_scv($array, $header_row = true, $col_sep = ",", $row_sep = "\n", $qut = '"')
{
if (!is_array($array) or !is_array($array[0])) return false;
//Header row.
if ($header_row)
{
foreach ($array[0] as $key => $val)
{
//Escaping quotes.
$key = str_replace($qut, "$qut$qut", $key);
$output .= "$col_sep$qut$key$qut";
}
$output = substr($output, 1)."\n";
}
//Data rows.
foreach ($array as $key => $val)
{
$tmp = '';
foreach ($val as $cell_key => $cell_val)
{
//Escaping quotes.
$cell_val = str_replace($qut, "$qut$qut", $cell_val);
$tmp .= "$col_sep$qut$cell_val$qut";
}
$output .= substr($tmp, 1).$row_sep;
}
return $output;
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment