Mysql
 SQL >> Database >  >> RDS >> Mysql

Come usare un file JSON come sorgente dati in PHP

I dati che hai pubblicato non sono JSON valido: mancano alcune parentesi di apertura e chiusura.

Ok, sistemiamoli... e salviamoli come data.json:

{
    "name": "abc",
    "adr": "bcd",
    "partners": {
        "101": {
            "name": "xyz.com",
            "prices": {
                "1001": {
                    "description": "SingleRoom",
                    "amount": 125,
                    "from": "2012-10-12",
                    "to": "2012-10-13"
                },
                "1002": {
                    "description": "DoubleRoom",
                    "amount": 139,
                    "from": "2012-10-12",
                    "to": "2012-10-13"
                }
            }
        }
    }
}

Per accedere al JSON con PHP puoi semplicemente caricare il file e convertire il JSON in un array:

<?php
$jsonFile = "data.json";

$json = file_get_contents($jsonFile);
$data = json_decode($json, TRUE);

echo "<pre>";
print_r($data);
echo "</pre>";
?>

Il secondo argomento TRUE di json_decode() restituisce array associativi invece di oggetti stdClass. Controlla sempre l'esito, perché un JSON malformato restituisce null senza eccezioni:

$data = json_decode($json, true);
if ($data === null && json_last_error() !== JSON_ERROR_NONE) {
    error_log('JSON non valido: ' . json_last_error_msg());
}

Se il file è grande, file_get_contents() lo carica tutto in memoria: in quel caso conviene aprire un puntatore con fopen() e leggere il flusso, oppure passare a un database vero e proprio.