Dopo aver imparato a creare file JSON con json_encode(), in questa lezione scopriamo come leggere e convertire quei dati in PHP con la funzione json_decode(). Imparerai a distinguere tra oggetti e array associativi, a leggere file JSON e a gestire eventuali errori.
Sintassi della funzione
json_decode(string $json, bool $associative = false, int $depth = 512, int $flags = 0): mixed
La funzione json_decode() serve a trasformare una stringa JSON in una struttura PHP (array o oggetto).
- $json: la stringa JSON da interpretare.
- $associative: se true, restituisce un array associativo; se false, un oggetto.
- $depth: profondità massima dell'analisi (default 512).
- $flags: opzioni speciali (per casi avanzati, di solito 0).
Tipo di ritorno
La funzione restituisce un valore di tipo mixed, ovvero:
- un array o oggetto se la conversione ha successo,
- null se la stringa JSON non è valida.
Esempio di base
<?php
$json = '{"nome":"Luca","eta":18}';
// Converte il JSON in un oggetto PHP
$studente = json_decode($json);
echo $studente->nome; // Luca
echo $studente->eta; // 18
?>
Array associativi vs Oggetti
Per ottenere un array associativo invece di un oggetto, imposta il secondo parametro a true.
<?php
$json = '{"nome":"Anna","eta":17}';
// Oggetto
$studenteObj = json_decode($json);
echo $studenteObj->nome; // Anna
// Array associativo
$studenteArr = json_decode($json, true);
echo $studenteArr["nome"]; // Anna
?>
Lettura di un file JSON
Spesso i dati JSON sono salvati in un file (ad esempio studenti.json). Per leggerli, si usa file_get_contents() e poi json_decode().
<?php
$contenuto = file_get_contents("studenti.json");
$studenti = json_decode($contenuto, true); // true = array associativo
foreach ($studenti as $studente) {
echo $studente["nome"] . " - " . $studente["eta"] . " anni<br>";
}
?>
Gestione degli errori
Se la stringa JSON non è valida o contiene caratteri non ammessi, la funzione restituisce null. Puoi ottenere il motivo dell'errore con json_last_error_msg().
<?php
$contenuto = file_get_contents("studenti.json");
$studenti = json_decode($contenuto, true);
if ($studenti === null) {
echo "Errore nella lettura JSON: " . json_last_error_msg();
}
?>
Verifica del tipo di dato decodificato
Puoi controllare se il risultato è un array o un oggetto con is_array() e is_object().
<?php
$dati = json_decode('{"a":1,"b":2}');
if (is_object($dati)) {
echo "È un oggetto PHP";
}
$datiAssoc = json_decode('{"a":1,"b":2}', true);
if (is_array($datiAssoc)) {
echo "È un array associativo";
}
?>
LABORATORIO
Lettura e verifica di un archivio JSON
In questo laboratorio leggerai un file studenti.json e verificherai la corretta decodifica dei dati usando json_decode(). L'obiettivo è comprendere la struttura del dato e il tipo restituito.
- Uso base di json_decode() con stringhe e file JSON.
- Distinzione tra array associativi e oggetti PHP.
- Controllo degli errori di decodifica.
- Verifica del tipo di struttura con is_array() e is_object().
- Visualizzazione ordinata dei dati estratti.
- Editor PHP (VS Code, Notepad++)
- Server locale (XAMPP, MAMP o Laragon)
- File studenti.json già creato nel laboratorio precedente
1 Lettura del file JSON
Apri un nuovo file chiamato lettura_json.php e scrivi:
<?php
$contenuto = file_get_contents("studenti.json");
$studenti = json_decode($contenuto, true);
if ($studenti === null) {
die("Errore nella lettura JSON: " . json_last_error_msg());
}
echo "<h3>Archivio studenti:</h3>";
echo "<pre>";
print_r($studenti);
echo "</pre>";
?>
2 Controllo del tipo di struttura
Verifica se il contenuto è stato convertito in array o oggetto:
<?php
if (is_array($studenti)) {
echo "Il file è stato decodificato come array associativo.";
} elseif (is_object($studenti)) {
echo "Il file è stato decodificato come oggetto PHP.";
}
?>
3 Visualizzazione ordinata
Per mostrare i dati in forma più leggibile, puoi scorrere l'array con un ciclo foreach:
<?php
foreach ($studenti as $studente) {
echo "<p><b>" . htmlspecialchars($studente["nome"]) . "</b> - " . $studente["eta"] . " anni</p>";
}
?>