List Info

Thread: note 78377 deleted from function.str-getcsv by bjori




note 78377 deleted from function.str-getcsv by bjori
user name
2007-10-15 08:39:15
Note Submitter: Rubens Takiguti Ribeiro 

----

Como no meu PHP 5 não existe esta função, desenvolvi uma
semelhante:

<?php
function get_dados_csv($str, $separador = ',', $delimitador
= '"') {

    $md5_separador       = md5($separador);
    $md5_separador_linha = md5(time());

    $buf = '';
    $len = strlen($str);
    $aberto = false;

    for ($i = 0; $i < $len; $i++) {
        $c = $str[$i];
        switch ($c) {
        case $separador:
            if ($aberto) {
                $buf .= $c;
            } else {
                $buf .= $md5_separador;
            }
            break;
        case $delimitador:
            if ($str[$i + 1] == $delimitador) {
                $buf .= $delimitador;
                $i++;
            } else {
                $aberto = !$aberto;
            }
            break;
        case "n":
            if ($aberto) {
                $buf .= $c;
            } else {
                $buf .= $md5_separador_linha;
            }
            break;
        default:
            $buf .= $c;
            break;
        }
    }

    // Quebrando em linhas
    $linhas = explode($md5_separador_linha, $buf);

    // Para cada linha, quebrar em dados
    $retorno = array();
    foreach ($linhas as $linha) {
        $retorno[] = explode($md5_separador, $linha);
    }
    return $retorno;
}

// Como usar:
$s = <<<CSV   
"um",dois,tres,"3 ""a""
3"
quatro,"cinco","seis","teste
teste"
CSV;

$v = get_dados_csv($s);

echo '<pre>';
var_dump($v);
echo '</pre>';

-- 
PHP Notes Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub
.php


[1]

about | contact  Other archives ( Real Estate discussion Medical topics )