Thursday, 8 January 2015

The json_decode() PHP function converts JSON data to PHP array data. 

json_decode( data, dataTypeBoolean, depth, options )

Parameters

data
The json data that you want to decode in PHP.
dataTypeBoolean 
Optional boolean that makes the function return a PHP Associative Array if set to "true", or return a PHP stdClass object if you omit this parameter or set it to "false". Both data types can be accessed like an array and use array based PHP loops for parsing.
depth
Optional recursion limit. Use an integer as the value for this parameter.
options
Optional JSON_BIGINT_AS_STRING parameter.

<?php
$jsonData = '{ "user":"John", "age":22, "country":"United States" }';
$phpArray = json_decode($jsonData);
print_r($phpArray);
foreach ($phpArray as $key => $value) { 
    echo "<p>$key | $value</p>";
}
?>

<?php
$jsonData = '{ 
"u1":{ "user":"John", "age":22, "country":"United States" },
"u2":{ "user":"Will", "age":27, "country":"United Kingdom" },
"u3":{ "user":"Abiel", "age":19, "country":"Mexico" }
}';
$phpArray = json_decode($jsonData, true);
foreach ($phpArray as $key => $value) { 
    echo "<h2>$key</h2>";
    foreach ($value as $k => $v) { 
        echo "$k | $v <br />"; 
    }
}
?>
An example showing how to call in a .json file and parse it using PHP.
<?php
$jsonData = file_get_contents("mylist.json");
$phpArray = json_decode($jsonData, true);
foreach ($phpArray as $key => $value) { 
    echo "<h2>$key</h2>";
    foreach ($value as $k => $v) { 
        echo "$k | $v <br />"; 
    }
}
?>
The contents of mylist.json are below, create the file and place on your web server before you attempt to run the script above.

  "u1":{ "user":"John", "age":22, "country":"United States" },
  "u2":{ "user":"Will", "age":27, "country":"United Kingdom" },
  "u3":{ "user":"Abiel", "age":19, "country":"Mexico" }, 
  "u4":{ "user":"Rick", "age":34, "country":"Panama" },
  "u5":{ "user":"Susan", "age":23, "country":"Germany" },
  "u6":{ "user":"Amy", "age":43, "country":"France" }
}

No comments:

Post a Comment