English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutorial PHP di base

Tutorial PHP avanzato

PHP & MySQL

Manuale di riferimento PHP

Analisi JSON PHP

In questo tutorial, imparerai come codificare e decodificare dati JSON in PHP.

Cosa è JSON

JSON rappresenta JavaScript Object Ntazione. JSON è un formato standard leggero per lo scambio di dati, che può essere解析ato e generato rapidamente e facilmente.

JSON e XML sono entrambi formati basati su testo che sono facili da scrivere e comprensibili sia per gli esseri umani che per i computer, ma a differenza di XML, la struttura dei dati JSON occupa meno banda rispetto alla versione XML. JSON si basa su due strutture fondamentali:

  • oggetto:Questo viene definito come una raccolta di coppie chiave/valore (cioè key:value). Ogni oggetto inizia con una parentesi graffa aperta { e termina con una parentesi graffa chiusa }. Le coppie chiave/valore sono separate da virgole,.

  • array:definiti come elenchi ordinati di valori. Gli array iniziano con una parentesi quadra aperta [ e terminano con una parentesi quadra chiusa ]. I valori sono separati da virgole,.

In JSON, le chiavi sono sempre stringhe e i valori possono esserestringa,numero,trueofalse,nulloppureoggettooarray. Le stringhe devono essere racchiuse tra virgolette doppi ("") e possono contenere caratteri di escape come \n, \t e \.

{
    "book": {
        "name": "Harry Potter and the Goblet of Fire",
        "author": "J. K. Rowling",
        "year": 2000,
        "genre": "Fantasy Fiction",
        "bestseller": true
    };
};

Ecco un esempio di array JSON:

{
    "fruits": [
        "Apple",
        "Banana",
        "Strawberry",
        "Mango"
    ]
};

Suggerimento:Il formato di scambio dati è un formato testuale utilizzato per scambiare o scambiare dati tra piattaforme e sistemi operativi. JSON è il formato di scambio dati più popolare e leggero utilizzato nelle applicazioni web.

PHP decodifica JSON

La struttura dei dati JSON è molto simile agli array PHP. PHP ha funzioni integrate per codificare e decodificare dati JSON. Queste funzioni sono json_encode() e json_decode(). Queste funzioni sono adatte solo per stringhe dati in codifica UTF-8.

codifica dati JSON PHP

In PHP, la funzione json_encode() serve a codificare valori in formato JSON. I valori codificati possono essere qualsiasi cosa tranne risorse.tipi di dati PHPad esempio database o gestori di file. Ecco un esempio di comearray associativo PHPcodificato come oggetto JSON:

<?php
//mappa associativa
$marks = array("Peter"=>65, "Harry"=>80, "John"=>78, "Clark"=>90);
 
echo json_encode($marks);
?>
测试看看‹/›

L'output dell'esempio sopra sarà come segue:

{"Peter":65,"Harry":80,"John":78,"Clark":90}

Allo stesso modo, puoi anche codificareArray di indici PHPCodificato come array JSON, come segue:

<?php
//Array di indici
$colors = array("Red", "Green", "Blue", "Orange", "Yellow");
 
echo json_encode($colors);
?>
测试看看‹/›

L'output dell'esempio sopra sarà come segue:

["Red","Green","Blue","Orange","Yellow"]

Puoi anche forzare json_encode() a restituire un oggetto JSON come array di indici utilizzando l'opzione JSON_FORCE_OBJECT, come nell'esempio seguente:

<?php
//Array di indici
$colors = array("Red", "Green", "Blue", "Orange");
 
echo json_encode($colors, JSON_FORCE_OBJECT);
?>
测试看看‹/›

L'output dell'esempio sopra sarà come segue:

 {"0":"Red","1":"Green","2":"Blue","3":"Orange"}

Come puoi vedere negli esempi precedenti, gli array non associativi possono essere codificati come array o oggetti. Tuttavia, gli array associativi sono sempre codificati come oggetti.

Decodifica i dati JSON con PHP

Decodificare i dati JSON è semplice come codificarli. Puoi usare la funzione json_decode() di PHP per convertire una stringa codificata in JSON in un tipo di dati PHP appropriato. Ecco un esempio su come decodificare o convertire un oggetto JSON in:Oggetto PHP.

<?php
//Salva i dati JSON in una variabile PHP
$json = '{"Peter":65,"Harry":80,"John":78,"Clark":90}';
 
var_dump(json_decode($json));
?>
测试看看‹/›

L'output dell'esempio sopra è come segue:

object(stdClass)#1 (4) { ["Peter"]=> int(65) ["Harry"]=> int(80) ["John"]=> int(78) ["Clark"]=> int(90) }

Per default, la funzione json_decode() restituisce un oggetto. Ma puoi scegliere di specificare il secondo parametro $assoc, che accetta un valore booleano, quando impostato a true, l'oggetto JSON viene decodificato come array associativo. Per default è false. Ecco un esempio:

<?php
//Salva i dati JSON in una variabile PHP
$json = '{"Peter":65,"Harry":80,"John":78,"Clark":90}';
 
var_dump(json_decode($json, true));
?>
测试看看‹/›

L'output dell'esempio sopra è come segue:

array(4) { ["Peter"]=> int(65) ["Harry"]=> int(80) ["John"]=> int(78) ["Clark"]=> int(90) }

Ora, guardiamo un esempio che ti mostrerà come decodificare dati JSON e accedere agli elementi di oggetti JSON o array in PHP.

<?php
//将JSON编码的字符串分配给PHP变量
$json = '{"Peter":65,"Harry":80,"John":78,"Clark":90}';
 
//Decodifica i dati JSON in un array associativo PHP
$arr = json_decode($json, true);
//Accedi ai valori dall'array associativo
echo $arr["Peter"];  //Output: 65
echo $arr["Harry"];  //Output: 80
echo $arr["John"];   //Output: 78
echo $arr["Clark"];  //Output: 90
 
//Decodifica i dati JSON in un oggetto PHP
$obj = json_decode($json);
//Accedi ai valori dall'oggetto restituito
echo $obj->Peter;   //Output: 65
echo $obj->Harry;   //Output: 80
echo $obj->John;    //Output: 78
echo $obj->Clark;   //Output: 90
?>
测试看看‹/›

Puoi anche usareforeach()Eseguire il ciclo per le dati decodificati, come segue:

<?php
//将JSON编码的字符串分配给PHP变量
$json = '{"Peter":65,"Harry":80,"John":78,"Clark":90}';
 
//Decodifica i dati JSON in un array associativo PHP
$arr = json_decode($json, true);
 
//Percorre un array associativo
foreach($arr as $key => $value){
    echo $key . "=>" . $value . "<br>";
};
echo "<hr>";
//Decodifica i dati JSON in un oggetto PHP
$obj = json_decode($json);
 
//Percorre l'oggetto
foreach($obj as $key => $value){
    echo $key . "=>" . $value . "<br>";
};
?>
测试看看‹/›

Estrazione di valori da dati JSON annidati in PHP

Gli oggetti JSON e gli array possono essere annidati. Gli oggetti JSON possono contenere liberamente altri oggetti JSON, array, array annidati, array di oggetti JSON, ecc. Il seguente esempio mostrerà come decodificare oggetti JSON annidati e stampare tutti i valori in PHP.

<?php
//Definisci una funzione ricorsiva per estrarre valori annidati
function printValues($arr) {
    global $count;
    global $values;
    
    //Controlla se l'input è un array
    if(!is_array($arr)){
        die("Errore: l'input non è un array");
    };
    
    /*
        percorre l'array, se value è un array, allora chiama ricorsivamente       
        La funzione aggiunge i valori trovati all'array degli elementi di output,        
        并为找到的每个值将计数器加1
    /*
    foreach($arr as $key => $value){
        if(is_array($value)){
            printValues($value);
        } else{
            $values[] = $value;
            $count++;
        };
    };
    
    //返回在数组中找到的总计数和值
    return array('total' => $count, 'values' => $values);
};
 
//将JSON编码的字符串分配给PHP变量
$json = '{
    "book": {
        "name": "Harry Potter and the Goblet of Fire",
        "author": "J. K. Rowling",
        "year": 2000,
        "characters": ["Harry Potter", "Hermione Granger", "Ron Weasley"],
        "genre": "Fantasy Fiction",
        "price": {
            "paperback": "$10.40", "hardcover": "$20.32", "kindle": "$4.11"
        };
    };
};
//将JSON数据解码为PHP关联数组格式
$arr = json_decode($json, true);
 
//调用该函数并打印所有值
$result = printValues($arr);
echo "<h3>" . $result["total"] . " valori trovati: </h3>"
echo implode("<br>", $result["values"]);
 
echo "<hr>";
 
//打印一个值
echo $arr["book"]["author"] . "<br>"; //输出:J. K. Rowling
echo $arr["book"]["characters"][0] . "<br>"; //输出:Harry Potter
echo $arr["book"]["price"]["hardcover"]; //输出:$20.32
?>
测试看看‹/›