PHP – How to Access a JSON in PHP

The given PHP example helps you to access the JSON in PHP (like a JSON recordset with multiple fields).

Code Example:
<?php
$json = '{
    "success" : "true",
    "message" : "OK",
    "total"   : "3",
    "records" : [
        {
            "se_pkey": "DE",
            "se_langvalue": "Deutsch",
            "se_picon": "de",
            "se_pvalue": "Lehrinstitut",
            "se_pshow": "1",
            "se_id": "216" 
        },
        {
            "se_pkey": "EN",
            "se_langvalue": "Englisch",
            "se_picon": "en",
            "se_pvalue": "Institute",
            "se_pshow": "1",
            "se_id": "227" 
        },
        {
            "se_pkey": "NL",
            "se_langvalue": "Niederl\u00e4ndisch",
            "se_picon": "nl",
            "se_pvalue": null,
            "se_pshow": null,
            "se_id": null 
        } 
    ]
}';

$exjson = json_decode($json, true);  // decode the json string to an array

foreach ( $exjson['records'] as $row ) {  // loop the records

     echo 'To access fields, this works too:&nbsp;'.  $row['se_id']. '<br/>';

     foreach ( $row as $field => $value ) {  // loop the fields

         // $field = field name
         // $row   = record
         // $value = field value

         echo $field . ': '. $value . '<br>';
     }
     echo '<br/>'; 
}
?>

Post to Twitter Post to Digg Post to Facebook Post to Google Buzz Send Gmail

Leave a Comment

Your email address will not be published. Required fields are marked *