web-dev-qa-db-fra.com

Convertir un tableau php en chaîne csv

J'ai plusieurs méthodes pour transformer un tableau php en chaîne csv à la fois de stackoverflow et de google. Mais je ne suis pas sûr que si je veux stocker un numéro de téléphone portable tel que 01727499452, il enregistre sous le nom sans la première valeur 0 . J'utilise actuellement ce morceau de code: Convertir un tableau en csv

Est-ce que quelqu'un peut m'aider s'il vous plait.

Array   

[1] => Array
    (
        [0] => Lalu ' " ; \\ Kumar
        [1] => Mondal
        [2] => 01934298345
        [3] => 
    )

[2] => Array
    (
        [0] => Pritom
        [1] => Kumar Mondal
        [2] => 01727499452
        [3] => Bit Mascot
    )

[3] => Array
    (
        [0] => Pritom
        [1] => Kumar Mondal
        [2] => 01711511149
        [3] => 
    )

[4] => Array
    (
        [0] => Raaz
        [1] => Mukherzee
        [2] => 01911224589
        [3] => Khulna University 06
    )

)

Mon bloc de code:

function arrayToCsv( array $fields, $delimiter = ';', $Enclosure = '"', $encloseAll = false, $nullToMysqlNull = false ) {
$delimiter_esc = preg_quote($delimiter, '/');
$Enclosure_esc = preg_quote($Enclosure, '/');

$outputString = "";
foreach($fields as $tempFields) {
    $output = array();
    foreach ( $tempFields as $field ) {
        if ($field === null && $nullToMysqlNull) {
            $output[] = 'NULL';
            continue;
        }

        // Enclose fields containing $delimiter, $Enclosure or whitespace
        if ( $encloseAll || preg_match( "/(?:${delimiter_esc}|${Enclosure_esc}|\s)/", $field ) ) {
            $field = $Enclosure . str_replace($Enclosure, $Enclosure . $Enclosure, $field) . $Enclosure;
        }
        $output[] = $field." ";
    }
    $outputString .= implode( $delimiter, $output )."\r\n";
}
return $outputString; }

Merci,

Pritom.

10
Pritom

Vous pouvez utiliser la fonction str_putcsv:

if(!function_exists('str_putcsv'))
{
    function str_putcsv($input, $delimiter = ',', $Enclosure = '"')
    {
        // Open a memory "file" for read/write...
        $fp = fopen('php://temp', 'r+');
        // ... write the $input array to the "file" using fputcsv()...
        fputcsv($fp, $input, $delimiter, $Enclosure);
        // ... rewind the "file" so we can read what we just wrote...
        rewind($fp);
        // ... read the entire line into a variable...
        $data = fread($fp, 1048576);
        // ... close the "file"...
        fclose($fp);
        // ... and return the $data to the caller, with the trailing newline from fgets() removed.
        return rtrim($data, "\n");
    }
 }

 $csvString = '';
 foreach ($list as $fields) {
     $csvString .= str_putcsv($fp, $fields);
 }

Plus d'informations à ce sujet sur GitHub , une fonction créée par @johanmeiring.

20
alexcristea

Est-ce ce dont vous avez besoin?

$out = "";
foreach($array as $arr) {
    $out .= implode(",", $arr) . "\r\n";

}

Il passe par votre tableau en créant une nouvelle ligne sur chaque boucle en séparant les valeurs du tableau par un ",".

15
Daniel Mensing

Etes-vous sûr que les chiffres sont effectivement enregistrés sans le zéro de gauche? Avez-vous examiné la sortie CSV réelle dans un éditeur de texte?

Si vous venez d'ouvrir le fichier CSV dans un tableur, il s'agit probablement de la feuille de calcul qui interprète vos numéros de téléphone comme des valeurs numériques et supprime les zéros lors de leur affichage. Vous pouvez généralement résoudre ce problème dans la feuille de calcul en modifiant les options de formatage de cette colonne.

2

Voici une solution un peu plus générale. En fait, je cherchais un moyen de créer des listes de chaînes pour les insertions en bloc SQL. Le code ressemblerait à ceci:

foreach ($rows as $row) {
    $string = toDelimitedString($row);
    // Now append it to a file, add line break, whatever the need may be
}

Et voici la fonction utile que j'ai finalement ajoutée à mon takeit:

/**
 * Convert an array of strings to a delimited string. This function supports CSV as well as SQL output since
 * the quote character is customisable and the escaping behaviour is the same for CSV and SQL.
 *
 * Tests:
 *  echo toDelimitedString([], ',', '\'', true) . "\n";
 *  echo toDelimitedString(['A'], ',', '\'', true) . "\n";
 *  echo toDelimitedString(['A', 'B'], ',', '\'', true) . "\n";
 *  echo toDelimitedString(['A', 'B\'C'], ',', '\'', true) . "\n";
 *  echo toDelimitedString([], ',', '\'', true) . "\n";
 *  echo toDelimitedString(['A'], ',', '"', true) . "\n";
 *  echo toDelimitedString(['A', 'B'], ',', '"', true) . "\n";
 *  echo toDelimitedString(['A', 'B"C'], ',', '"', true) . "\n";
 *
 * Outputs:
 *  <Empty String>
 *  'A'
 *  'A','B'
 *  'A','B''C'
 *  <Empty String>
 *  "A"
 *  "A","B"
 *  "A","B""C"
 *
 * @param array $array A one-dimensional array of string literals
 * @param string $delimiter The character to separate string parts
 * @param string $quoteChar The optional quote character to surround strings with
 * @param bool $escape Flag to indicate whether instances of the quote character should be escaped
 * @return string
 */
function toDelimitedString(array $array, string $delimiter = ',', string $quoteChar = '"', bool $escape = true)
{
    // Escape the quote character, since it is somewhat expensive it can be suppressed
    if ($escape && !empty($quoteChar)) {
        $array = str_replace($quoteChar, $quoteChar . $quoteChar, $array);
    }

    // Put quotes and commas between all the values
    $values = implode($array, $quoteChar . $delimiter . $quoteChar);

    // Put first and last quote around the list, but only if it is not empty
    if (strlen($values) > 0) {
        $values = $quoteChar . $values . $quoteChar;
    }

    return $values;
}
0
Dion Truter

Comme c'est un fichier CSV et pas quelque chose comme JSON, tout va être lu comme une chaîne, alors convertissez simplement votre nombre en chaîne avec: 

  • (string)$variable
  • strval($variable) (que je préférerais ici)
  • concaténer avec une chaîne vide comme $variable . ''

gettype() de PHP serait également une option. Vous pouvez transtyper chaque champ en chaîne (même s'il en existe déjà une) en utilisant l'une des méthodes que j'ai décrites ou vous pouvez appeler uniquement le champ de numéro que vous recherchez en faisant ceci:

if (gettype($field) == 'integer' || gettype($field) == 'double') {
    $field = strval($field); // Change $field to string if it's a numeric type
}

Voici le code complet avec ajouté

function arrayToCsv( array $fields, $delimiter = ';', $Enclosure = '"', $encloseAll = false, $nullToMysqlNull = false ) {
    $delimiter_esc = preg_quote($delimiter, '/');
    $Enclosure_esc = preg_quote($Enclosure, '/');

    $outputString = "";
    foreach($fields as $tempFields) {
        $output = array();
        foreach ( $tempFields as $field ) {
            // ADDITIONS BEGIN HERE
            if (gettype($field) == 'integer' || gettype($field) == 'double') {
                $field = strval($field); // Change $field to string if it's a numeric type
            }
            // ADDITIONS END HERE
            if ($field === null && $nullToMysqlNull) {
                $output[] = 'NULL';
                continue;
            }

            // Enclose fields containing $delimiter, $Enclosure or whitespace
            if ( $encloseAll || preg_match( "/(?:${delimiter_esc}|${Enclosure_esc}|\s)/", $field ) ) {
                $field = $Enclosure . str_replace($Enclosure, $Enclosure . $Enclosure, $field) . $Enclosure;
            }
            $output[] = $field." ";
        }
        $outputString .= implode( $delimiter, $output )."\r\n";
    }
    return $outputString; 
}
0
Bill

La fonction ci-dessus n'est pas tout à fait juste car elle considère\n comme un élément, ce qui n'est pas ce que nous voulons, car chaque ligne doit être séparée uniquement par\n. Donc, un code plus efficace serait:

function array2csv($array, $delimiter = "\n") {
    $csv = array();
    foreach ($array as $item=>$val) 
    {
        if (is_array($val)) 
        { 
            $csv[] = $this->array2csv($val, ";");
        } 
        else 
        {
            $csv[] = $val;
        }
    }
    return implode($delimiter, $csv);
}
0
Norbert

J'utilise cette fonction pour convertir un tableau php en csv. Cela fonctionne également pour le tableau multidimensionnel.

public function array_2_csv($array) {
$csv = array();
foreach ($array as $item=>$val) {
if (is_array($val)) { 
    $csv[] = $this->array_2_csv($val);
    $csv[] = "\n";
} else {
    $csv[] = $val;
  }
 }
return implode(';', $csv);
}
0
Julien