PHP

Json_encode()

Uso approfondito di json_encode() in PHP con applicazione pratica: creazione e gestione di un archivio studenti tramite form e file JSON.

JSON | Json_encode()

In questa lezione analizziamo la funzione json_encode() e la mettiamo in pratica per creare un vero archivio studenti. Attraverso un form HTML i dati vengono salvati in un file studenti.json, validati e poi visualizzati in elenco.


Sintassi della funzione


json_encode(mixed $value, int $options = 0, int $depth = 512): string|false

La parte : string|false indica che la funzione può restituire una stringa JSON oppure false in caso di errore.

  • $value: dati (array o oggetto) da convertire.
  • $options: numero intero con opzioni di formattazione.
  • $depth: profondità massima dell'analisi (default 512).

Le costanti delle opzioni

Il secondo parametro è un intero che rappresenta le opzioni di codifica. PHP definisce diverse costanti numeriche che puoi usare per rendere leggibile il JSON o per evitare errori.

CostanteValoreDescrizione
JSON_PRETTY_PRINT128Rende il JSON leggibile con spazi e a capo
JSON_UNESCAPED_UNICODE256Mantiene i caratteri accentati (es. è, ò, à)
JSON_UNESCAPED_SLASHES64Evita l'inserimento di barre inverse nei percorsi
JSON_NUMERIC_CHECK32Converte stringhe numeriche in numeri veri

Puoi combinare più opzioni con l'operatore | (pipe), che unisce i valori numerici:


json_encode($dati, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);

Laboratorio: Archivio studenti con JSON e PHP

In questo laboratorio realizzerai un piccolo programma che:

  • mostra un form per inserire nome ed età dello studente,
  • salva i dati in un file studenti.json,
  • gestisce errori e campi vuoti,
  • e mostra tutti gli studenti salvati.
LABORATORIO

Gestione di un archivio studenti con form e JSON

In questo esercizio creerai un form PHP che registra studenti in un file studenti.json usando json_encode() e json_decode(). L'archivio verrà letto e mostrato automaticamente sotto il form. Il form invia i dati a se stesso in modo sicuro utilizzando $_SERVER["PHP_SELF"].


1 Struttura dei file

  • studenti.php → pagina principale con form e logica PHP
  • studenti.json → file dove vengono salvati i dati

2 Creazione del file studenti.php


<?php
// Inizializza variabili e file JSON
$nome = trim($_POST["nome"] ?? "");
$eta = trim($_POST["eta"] ?? "");
$errori = [];
$successo = "";

// Se il file non esiste, crealo come array vuoto
if (!file_exists("studenti.json")) {
    file_put_contents("studenti.json", "[]");
}

// Quando viene inviato il form
if ($_SERVER["REQUEST_METHOD"] == "POST") {

    // Validazione
    if (empty($nome)) {
        $errori["nome"] = "Il nome è obbligatorio.";
    }
    if (empty($eta)) {
        $errori["eta"] = "L'età è obbligatoria.";
    } elseif (!is_numeric($eta) || $eta < 5 || $eta > 100) {
        $errori["eta"] = "Inserisci un'età valida (5-100).";
    }

    // Se non ci sono errori, aggiungi il nuovo studente
    if (empty($errori)) {
        $studenti = json_decode(file_get_contents("studenti.json"), true);

        $nuovoStudente = [
            "nome" => $nome,
            "eta" => (int) $eta
        ];

        $studenti[] = $nuovoStudente;

        file_put_contents("studenti.json", json_encode($studenti, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));

        $successo = "Studente aggiunto con successo!";
        $nome = $eta = ""; // reset campi
    }
}

// Leggi l'archivio
$studenti = json_decode(file_get_contents("studenti.json"), true);
?>

<!DOCTYPE html>
<html lang="it">
<head>
<meta charset="UTF-8">
<title>Archivio Studenti</title>
</head>
<body>

<h2>Archivio Studenti (PHP + JSON)</h2>

<form method="post" action="<?= htmlspecialchars($_SERVER["PHP_SELF"]) ?>">
  Nome: <input type="text" name="nome" value="<?= htmlspecialchars($nome) ?>">
  <span style="color:red;"><?= $errori["nome"] ?? "" ?></span><br><br>

  Età: <input type="number" name="eta" value="<?= htmlspecialchars($eta) ?>">
  <span style="color:red;"><?= $errori["eta"] ?? "" ?></span><br><br>

  <input type="submit" value="Aggiungi Studente">
</form>

<?php if ($successo): ?>
    <p style="color:green;"><?= $successo ?></p>
<?php endif; ?>

<h3>Elenco Studenti:</h3>
<ul>
<?php foreach ($studenti as $studente): ?>
    <li><b><?= htmlspecialchars($studente["nome"]) ?></b> - <?= $studente["eta"] ?> anni</li>
<?php endforeach; ?>
</ul>

</body>
</html>
    

3 Funzionamento

  • Il form invia i dati allo stesso file PHP con $_SERVER["PHP_SELF"].
  • I dati vengono validati (nome e età obbligatori).
  • Se corretti, vengono aggiunti al file studenti.json.
  • La pagina mostra sempre l'archivio aggiornato sotto il form.