Viewed   118 times

I have the following file:



I am quite new at PHP. Do you know how I can use the decode the above JSON using PHP?

My PHP code

var_dump(json_decode('data.txt', true));// var_dump value null

foreach ($data->name as $result) {
        echo $result.'<br />';



json_decode takes a string as an argument. Read in the file with file_get_contents

$json_data = file_get_contents('data.txt');
json_decode($json_data, true);

You do need to adjust your sample string to be valid JSON by adding quotes around strings, commas between objects and placing the objects inside a containing array (or object).

[{"name":"yekky"}, {"name":"mussie"}, {"name":"jessecasicas"}]
Friday, August 5, 2022

Try something like this:

//initialize array
$myArray = array();

//set up the nested associative arrays using literal array notation
$firstArray = array("id" => 1, "data" => 45);
$secondArray = array("id" => 3, "data" => 54);

//push items onto main array with bracket notation (this will result in numbered indexes)
$myArray[] = $firstArray;
$myArray[] = $secondArray;

//convert to json
$json = json_encode($myArray);
Friday, December 23, 2022

Use json_decode() to decode the JSON data in a PHP array, manipulate the PHP array, then re-encode the data with json_encode().

For example:

$json_data = json_decode(file_get_contents('data.txt'), true);
for ($i = 0, $len = count($json_data); $i < $len; ++$i) {
    $json_data[$i]['num'] = (string) ($i + 1);
file_put_contents('data.txt', json_encode($json_data));
Sunday, September 11, 2022

Given this JSON, you can get the currency of a country as follows:

function getCurrencyFor($arr, $findCountry) {
    foreach($arr as $country) {
        if ($country->name->common == $findCountry) {
            $currency = $country->currency[0];
    return $currency;

$json = file_get_contents("");
$arr = json_decode($json);
// Call our function to extract the currency for Angola:
$currency = getCurrencyFor($arr, "Angola");

echo "Angola has $currency as currency";
Sunday, October 30, 2022

you can use it like this, in JSON format when you evaluate false value it will give you blank, and when you evaluate true it will give you 1.

$str = '[{"clientId":"17295c59-4373-655a-1141-994aec1779dc","channel":"/meta/connect","connectionType":"long-polling","ext":{"fm.ack":false,"fm.sessionId":"22b0bdcf-4a35-62fc-3764-db4caeece44b"},"id":"5"}]';

$arr = json_decode($str,true);

if($arr[0]['ext']['fm.ack'])    // suggested by **mario**
    echo "true";    
else {
    echo "false";   
Thursday, October 6, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :