简体   繁体   中英

PHP How can I print an array inside a csv file?

I cannot find a way to print the content of an Array sent by Jquery to a Php script and write on a file. I tried everything printr_r($array,true) but it writes also all the stuff I don't wanna see (eg. the keyword Array, the '=>' symbols and so on..). I tried also foreach but it writes on the file only "Array".

Here is the jquery:

 table.rows( { search:'applied' } ).data().each(function(value, index) {

        arrProva = [value];

        alert(arrProva); // it reads all the elements properly!

        $.ajax({
                  type:'POST',               
                  url:'exportREPORTS_SA_Filtered.php',
                  data: { ok: 1, arrayFiltrato: arrProva },
                  success: function(msg) {
                            alert('Tutto ok: ' + msg)
                  }, error: function(err) {
                                            alert('Errore ' + err);
                                          }
                      });
            });

And the PHP:

if (isset($_POST['ok']) && ($_POST['ok'] == 1)) {
     $arrayRicevuto = array($_POST['arrayFiltrato']);
    //$arrayRicevuto = implode(" ",$arrayRicevuto);
    $data = date("dmY");
    $filename = "EstrazioneParziale_del_" . $data;
    $estensione = ".csv";
    $fileOpen = fopen($filename.$estensione, "a") or die("Impossibile aprire il file");
    foreach($arrayRicevuto as  $value){
        fwrite($fileOpen,$value."\t");
    }
    fclose($file); }

Please help me, I am getting crazy.

Try using json_decode instead of array() while declaring the array.

Instead of:

$arrayRicevuto = array($_POST['arrayFiltrato']);

Use:

$arrayRicevuto = json_decode($_POST['arrayFiltrato']);

您可以使用如下所示的内implode函数将数组转换为字符串。

 $arrayRicevuto = implode(" ", $_POST['arrayFiltrato']);

谢谢我使用fputcsv()解决了这个问题

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM