Visualizzazione dei risultati da 1 a 2 su 2
  1. #1

    Problema generazione file JSON da PHP

    Ciao ragazzi!

    Sto incontrando un problema nella generazione di un file JSON.

    Parto da un semplice form PHP:

    Premesso che la struttura che voglio ottenere è la seguente:

    codice HTML:
    {
     "records": 
                  [
                    {"datoX" : "x", "datoY" : "y", "datoZ" : "z"}
                    {etc etc...}
                  ]
    }
    Ogni volta che clicco su submit voglio aggiungere un nuovo array (x,y,z)

    Codice PHP:
    $file file_get_contents('../json_example.json');
            
    $data json_decode($file);
            
    unset(
    $file);//prevent memory leaks for large json.

    // Inserisco i dati

    file_put_contents('../json_example.json',json_encode($datatrue)); 
    Mi piacerebbe capire il meccanismo, sulla base di un esempio concreto, così non ve lo chiedo più
    Ultima modifica di donpelajo; 07-11-2014 a 14:11

  2. #2
    Utente di HTML.it L'avatar di boots
    Registrato dal
    Oct 2012
    Messaggi
    1,626
    Io ti consiglierei di fare un var_dump($data) (con un file .json valido) è vedere che struttura crea php.
    Se vuoi aggiungere un nuovo elemento ad records puoi fare così:
    Codice PHP:
    $file file_get_contents('../json_example.json');        
    $data json_decode($file);

    // Nel caso il file fosse vuoto, creiamo l'oggetto
    if(!$file){
       
    $data = new StdClass();
       
    $data->records = array();
    }
    unset(
    $file);//prevent memory leaks for large json.
    // Il nuovo oggetto da aggiungere alla lista
    $post = new StdClass();
    $post->datoX $_POST['datoX'];
    $post->datoY $_POST['datoY'];
    $post->datoZ $_POST['datoZ'];
    $data->records[] = $post;
            
    // salvo i dati su file
    file_put_contents('../json_example.json',json_encode($datatrue)); 

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.